Which array iteration method should you use for each job?
Choose the method by thinking about the shape of the answer that you want. If you want a new array of changed values, use map. If you want a smaller group, use filter. If you want a single value, use reduce. If you only want to run something for each item, use forEach. If you want a yes-or-no answer, use some or every. If you want the one item that matches, use find.
const scores = [12, 45, 78, 91];
// forEach: do something for each item, and build no new array.
let total = 0;
scores.forEach(function (score) {
total = total + score;
});
console.log(total); // 226
// map: change every item into a new array of the same length.
const marks = scores.map(function (score) {
return score / 10;
});
console.log(marks); // 1.2, 4.5, 7.8, 9.1
// filter: keep only the items that match.
const high = scores.filter(function (score) {
return score >= 50;
});
console.log(high); // 78, 91
// find: only the first match.
console.log(scores.find(function (score) {
return score > 50;
})); // 78
// some and every: yes-or-no questions.
console.log(scores.some(function (score) {
return score > 90;
})); // true
console.log(scores.every(function (score) {
return score > 10;
})); // true
Two differences are worth making clear. some and every stop early, so some stops as soon as it finds a true result and every stops at the first false one. find and findIndex stop early as well, which is why they are cheaper than filter when you only want the first match.
And forEach is the one that people use wrongly most often. It gives back nothing, so you cannot chain it, and using it to build a new array means that you are changing a variable from outside the callback. That is exactly the problem that map exists to solve.
One more difference catches people out. map and filter skip the gaps in a sparse array, and map leaves those gaps in the result. If your array might have gaps, fill it in before you change it.