Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break out of map

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;
  }
});
like image 939
Benas Lengvinas Avatar asked Apr 08 '18 12:04

Benas Lengvinas


People also ask

How do you break out of a map loop?

To break a map() loop in React: Call the slice() method on the array to get a portion of the array.

Can you break from map?

Not possible, We can't break #array. map, it will run for each element of array.

Is .map destructive?

map() is a non-destructive method.

What is Unsyntactic break?

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.


3 Answers

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;
 }
like image 69
Jonas Wilms Avatar answered Oct 17 '22 01:10

Jonas Wilms


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

like image 20
Muhammad Usman Avatar answered Oct 17 '22 00:10

Muhammad Usman


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.

like image 3
Willem van der Veen Avatar answered Oct 17 '22 00:10

Willem van der Veen