Array reduce is one of the Array.prototype functions, that was added to javascript from ECMAScript 5. All browsers support this method.

This method executes a reducer function on each element of the array, resulting in single output value.

How does reduce work?

The reduce method takes two arguments: a reducer function and an initial value that will be passed to reducer.

The reducer function takes four arguments: accumulator, current, index, and array.

const reduced = arr.reduce( callback( accumulator, current [, index [, array ]] )[, initialValue ]);

The returned value from reducer is assigned to accumulator, which in each iteration of array elements, its value is preserved. The final result of reduce function will be this value. initialValue sets the accumulator value on the first element. Its default value is 0.

current represents current value in array, and index is obviously its index in the array. and finally, the array represents the whole array which this method is running on.

Examples

Calculate Array Sum

1
2
const values = [2.3, 3.4, 5.6, 2.4, 3.5];
const sum =  values.reduce( (total, each) => total+each );

This function adds each element's value to total.

Calculate Array Max

1
2
const values = [2.3, 3.4, 5.6, 2.4, 3.5];
const max =  values.reduce( (accumulator, each) => each>accumulator?each:accumulator );

In this example the function checks each element's value against accumulator. If element's value is bigger than accumulator, the accumulator will be re-set to element's value.

Calculate Array Min

1
2
const values = [2.3, 3.4, 5.6, 2.4, 3.5];
const max =  values.reduce( (accumulator, each) => each<accumulator?each:accumulator , Infinity);

In this example, the reduce starts with an initial value. Infinity.

Calculate Repetition Of Elements

1
2
3
4
5
6
const zoo = ['bear', 'goat', 'fish', 'goat', 'bear', 'rhino', 'cow', 'cow'];
const count =  zoo.reduce( (accumulator, each) => {
  accumulator[each] = (accumulator[each] || 0) + 1;
  return accumulator;
} , {});
// {bear: 2, goat: 2, fish: 1, rhino: 1, cow: 2}

Flat A 2D Array

1
2
3
const values = [[1.1, 2.1, 3.1], [1.2, 2.2, 3.2], [1.3, 2.3, 3.3]];
const flat =  values.reduce( (accumulator, each) => accumulator.concat(each), []);
// [1.1, 2.1, 3.1, 1.2, 2.2, 3.2, 1.3, 2.3, 3.3]