JavaScript Arrays Map, Reduce and Filter
Consider the following array that lists population and GDP (in millions) of various countries:
What if you wanted to calculate the combined GDP of all countries with a population less than 10 million? The iterative approach would look something like this:
With the fuctional approach using map, reduce and filter you can write the whole thing in one line:
So, what is going on here?
Filter phase
First we use the Array.prototype.filter to extract all countries with population less than 10 million. The function you pass to the filter method is expected to return true/false. Returning true will put the current element in the output-array while returning false will leave it out. So this will leave us with:
Map phase
We now use map to give us an array with only the gdp values of each country. Map will return an array of equal length to the original, but with altered entries. Here we specify to leave everything out but the gdp value which gives us:
Reduce phase
In the last step we use reduce to calculate the cumulated value of all three entries. This leads to the endresult of:
You can think of this in terms of an SQL statement:
with SELECT corresponding to the map phase, WHERE corresponding to the filter phase and the summing up corresponding to the reduce phase.
Check out this SQLFiddle (yes, that really is a thing…)
Wrapping up
So, while this is probably not a good choice when you have to keep an eye on performance,
it can greatly enhance readability and is much more versatile as you can plug in different functions in each of the phases to extract the data you want.