Coded-Aesthetics

Wrap your head around JavaScript Array.prototype.reduce

The reduce function let's you iterate over the array's elements and boil it down to a single value.

Consider we have the following array:

let arr = [3, 7, 9, 13];

and we want to calculate the sum of all its elements. The traditional (iterative) way would look like this:

var sum = 0;
for (var i = 0; i < arr.length; i++) {
    sum += arr[i];
}

With Array.reduce we can condens this into a one-liner:

let sum = arr.reduce(reducer);

With reducer being defined as follows:

function reducer(reductionSoFar, currentArrayElement, index)  {
    return reductionSoFar + currentArrayElement;
}

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.

arr.reduce(reducer, startValue);

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:

JsFiddle
let arr = [
  {name:"John", score: 12}, 
  {name:"Sylvia", score:15}, 
  {name:"Susan", score:22}
];
const reducer = (red, cur) => {
  red[cur.name] = cur.score;
  return red;
}
let scores = arr.reduce(reducer, {});

This will convert the array into an object with names as keys and scores as values.

/** scores will look like this:
    {'John':12, 'Sylvia': 15, 'Susan': 22}
**/