Wrap your head around JavaScript Array.prototype.reduce
Consider we have the following array:
and we want to calculate the sum of all its elements. The traditional (iterative) way would look like this:
With Array.reduce we can condens this into a one-liner:
With reducer being defined as follows:
Take a look at each iteration-step and what is passed to the reducer function:
Here is our array again:
[3, 7, 9, 13]
Step # | reductionSoFar | currentArrayElement | index | reduce function output: |
1 | 3 | 7 | 1 | 3 + 7 = 10 |
2 | 10 | 9 | 2 | 10 + 9 = 19 |
3 | 19 | 13 | 3 | 19 + 13 = 32 |
= 32
Note that in each step, the reductionSoFar variable is assigned the return value of the reducer function and it is is initialized with the first element of the array.
Supplying an initial value
You can pass an optional second argument to the array.reduce function, that serves as initialization of the reductionSoFar variable.
Consider we’d pass 10 as second argument like so:
arr.reduce(reducer, 10);
our iterations would now look like this:
[3, 7, 9, 13]
Step # | reductionSoFar | currentArrayElement | index | reduce function output: |
1 | 10 | 3 | 0 | 10 + 3 = 13 |
2 | 13 | 7 | 1 | 13 + 7 = 20 |
2 | 20 | 9 | 2 | 20 + 9 = 29 |
3 | 29 | 13 | 3 | 29 + 13 = 42 |
= 42
The only difference being, that the first value of reductionSoFar now is 10 and the function is called four times starting with arr[0] as currentArrayElement.
Of course you are not limited in what you supply as the initial value. Consider this example where we pass an object:
This will convert the array into an object with names as keys and scores as values.