so i have this problem where if the value in the array is higher than entered value it should do something and then stop the loop and don't touch the remaining values in the array.. Here's the code so far:
const percentages = [];
let enteredValue = parseInt(event.target.value, 10);
range.map((rangeValue, i) => {
if (rangeValue <= enteredValue) {
percentages.push(100);
enteredValue = enteredValue - rangeValue;
} else {
percentages.push(enteredValue * 100 / (rangeValue));
return;
}
});
To break a map() loop in React: Call the slice() method on the array to get a portion of the array.
Not possible, We can't break #array. map, it will run for each element of array.
map() is a non-destructive method.
The "Unsyntactic break" error occurs when we try to use a break statement outside of a for loop, or inside of a function in the for loop.
Just use a good old for loop:
const percentages = [];
let enteredValue = parseInt(event.target.value, 10);
for(const range of ranges) {
percentages.push(Math.min(100, (enteredValue / range) * 100));
enteredValue -= range;
if(enteredValue <= 0) break;
}
Using .some
you can get iteration functionally similar to .forEach
, map
or for
loop but with the ability to break
through return
instead.
range.some(function(rangeValue , i) {
if (rangeValue <= enteredValue) {
percentages.push(100);
enteredValue = enteredValue - rangeValue;
return true
}
percentages.push(enteredValue * 100 / (rangeValue));
});
Read more about .some
in es6
here
The other answers are perfectly sufficient. However, I would like to add that the map
function isn't best used for performing iterations. What the map
function does is perform the as argument passed in callback on every element of the array. It then returns the new array. So map is more usefull when you are in need of a mutated copy of the Array (e.g. all the elements multiplied by 10).
For your purposes other logic like a regular for loop will be a more elegant solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With