What if you have an array, but only want some of the elements in it? That’s where <span style="color: #000000;">.filter()</span> comes in!
Combining .map(), .reduce(), and .filter()
Since all three are called on arrays and since <span style="color: #000000;">.map()</span> and <span style="color: #000000;">.filter()</span> both return arrays, we can easily chain our calls.
And now here’s the fun part… we can chain all of this to get what we want in a single line:
var totalJediScore = personnel
.filter(function (person) {
return person.isForceUser;
})
.map(function (jedi) {
return jedi.pilotingScore + jedi.shootingScore;
})
.reduce(function (acc, score) {
return acc + score;
}, 0);
And look how pretty it is with arrow functions:
const totalJediScore = personnel .filter(person => person.isForceUser) .map(jedi => jedi.pilotingScore + jedi.shootingScore) .reduce((acc, score) => acc + score, 0);