Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break statement in javascript array map method [duplicate]

Tags:

javascript

People also ask

Can we use break in map JavaScript?

javascript break out of map // You cannot break out of `Array. protoype. map`.

Can we break a map function?

Not possible, We can't break #array. map, it will run for each element of array. To solve your problem, you can use slice first then map, slice first 5 elements of array then run map on that.

Does map return a copy?

map always returns an array. It doesn't matter how you use that return value.


That's not possible using the built-in Array.prototype.map. However, you could use a simple for-loop instead, if you do not intend to map any values:

var hasValueLessThanTen = false;
for (var i = 0; i < myArray.length; i++) {
  if (myArray[i] < 10) {
    hasValueLessThanTen = true;
    break;
  }
}

Or, as suggested by @RobW, use Array.prototype.some to test if there exists at least one element that is less than 10. It will stop looping when some element that matches your function is found:

var hasValueLessThanTen = myArray.some(function (val) { 
  return val < 10;
});