Simplify your JavaScript – Use .map(), .reduce(), and .filter()
.map()
Let me explain how it works with a simple example. Say you have received an array containing multiple objects – each one representing a person. The thing you really need in the end, though, is an array containing only the id of each person.
.reduce()
Just like
<span style="color: #000000;">.map()</span>
,<span style="color: #000000;">.reduce()</span>
also runs a callback for each element of an array. What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other..filter()
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!
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);