Break statement in javascript array map method [duplicate]
Solution 1:
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;
});