N.B- we can iterate an array using foreach and map in javascript like below-
var arrays = [1,2,3,4,5];
foreach():
arrays.forEach(function(cur){
if(cur===1){
break; //break and continue is illegal in foreach .
} console.log(cur);
});
You are passing a callback function.
break only works inside actual loops.
map():
map() is meant to transform an array and return a new array.
arrays.map(function(cur){
if(cur===2){
break; //break and continue is illegal in map.
}
console.log(cur);
});
so the solution is to use regular for loop.
const result = [1,2,3].map(function(cur){
Output: [1,100,3]
return only returns for that one callback execution, not the whole iteration.
//ES5
for(var i=0;i<arrays.length;i++){
if(i===3){
break;
}
console.log(arrays[i]);
}
//ES6
const arrays = [7,1,2,3,4,5];
for(const cur of arrays){
if(cur===3){
continue;
}
console.log(cur);
}
we can use for--of loop to iterate easily over an array in ES6.
filter():
filter() → keep only elements that match a condition.
const nums = [1,2,3,4];
const result = nums.filter(function(cur){
return cur > 2;
});
console.log(result);
output:[3,4]
It creates a new array containing only the elements that passed the condition.
find():
find() → returns first matching element only (single value)