reduce()

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

const total = [0, 1, 2, 3].reduce((sum, value) => sum + value, 0);
// total is 6

const flattened = [[0, 1], [2, 3], [4, 5]].reduce((a, b) => a.concat(b), []);
// flattened is [0, 1, 2, 3, 4, 5]
Syntax
arr.reduce(callback[, initialValue])
Parameters

callback

Function to execute on each element in the array, taking four arguments:

accumulator

The accumulator accumulates the callback's return values; it is the accumulated value previously returned in the last invocation of the callback, or initialValue, if supplied (see below).

currentValue

The current element being processed in the array.

currentIndex

The index of the current element being processed in the array. Starts at index 0, if an

initialValue

is provided, and at index 1 otherwise.

array

The array reduce was called upon.

initialValue

[Optional] Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce on an empty array without an initial value is an error.

How reduce works

Suppose the following use of reduce occurred:

[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => accumulator + currentValue);

The callback would be invoked four times, with the arguments and return values in each call being as follows:

callback accumulator currentValue currentIndex array return value
first call 0 1 1 [0, 1, 2, 3, 4] 1
second call 1 2 2 [0, 1, 2, 3, 4] 3
third call 3 3 3 [0, 1, 2, 3, 4] 6
fourth call 6 4 4 [0, 1, 2, 3, 4] 10

The value returned by reduce would be that of the last callback invocation (10).

Counting instances of values in an object

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce((allNames, name) => { 
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

Bonding arrays contained in an array of objects using the spread operator and initialValue

// friends - an array of objects 
// where object field "books" - list of favorite books 
var friends = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}];

// allbooks - list which will contain all friends' books +  
// additional list contained in initialValue
var allbooks = friends.reduce((prev, curr) => [...prev, ...curr.books], ['Alphabet']);

// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace', 
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]

results matching ""

    No results matching ""