.reduce()

.reduce()

  • .reduce() is used calculate a single value based on the array

  • A reducer function (that you provide) is called on each element of the array and results in a single output value

  • Often used to perform a calculation that accepts all the elements of an array (usually numbers) as inputs

    • For example: Calculating the sum of all the items in an array
  • .reduce() accepts the following parameters

  • The callback function (also referred to the reducer function in this case) for .reduce() accepts the following parameters:

    • accumulator: (required) the accumulated value previously returned in from the last iteration;

    • currentValue: (required) current element being processed in the array.

    • index: (optional) index of the current element being processed in the array

    • array: (optional) the array map was called upon

  • initialValue: (optional) the value to use as the first argument to for the first iteration of reduce(); If no initialValue is supplied, the first element in the array will be used


Syntax

Using traditional (ES5) function syntax

const value = arr.reduce(function(previousValue, item, index, array) {
  // ...
}, [initial]);

Using arrow syntax (ES6)

const value = arr.reduce((previousValue, item, index, array) => {
  // ...
}, [initial]);

Example

  • Example where no initialValue is supplied
const numbers = [1, 2, 3, 4, 5]

const result = numbers.reduce((sum, currentNumber) => {
  return sum + currentNumber
})

console.log(result) // 15

JS Bin on jsbin.com

  • Example where we set the initialValue to 10
const numbers = [1, 2, 3, 4, 5]

const result = numbers.reduce((sum, currentNumber) => {
  return sum + currentNumber
}, 10)

console.log(result) // 25

JS Bin on jsbin.com


Exercise

Use .reduce() to calculate the sum of the numbers found in the amounts array; Save the result in a variable declared with const called total

JS Bin on jsbin.com