.reduce()

The .reduce() array method combines each element of an array, using a reducer function you specify, and returns a single value.

Syntax

Loading...

The reducer function takes four arguments:

  • accumulator is the returned value from the function.
  • currentValue is the element being iterated over.
  • index (optional) is the index of the currentValue.
  • array (optional) is the array the .reduce() was called on.

The accumulator‘s value accumulates with each iteration through the array, resulting in a single value.

.reduce() takes two arguments:

  • The first, is the reducer function that performs the reduction operation.
  • The second (optional) argument is an initial value to pass to the function.

For example:

Loading...

Example 1

Add strings in an array.

Loading...

Example 2

Add the values of each element together with an initial value.

Loading...

Example 3

Subtract numbers in an array with initial value provided:

Loading...
Interested in helping build Docs? Read the Contribution Guide or share your feedback.

Learn JavaScript on Codecademy