.reduce()

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

Syntax

array.reduce((accumulator, currentValue, index, array) => {...}, initialValue)

.reduce() takes two arguments:

  • The first, is the reducer function that performs the reduction operation and 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 second (optional) argument is an initialValue to pass to the function.

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

Example

const arrayOne = ['a', 'b', 'c', 'd', 'e'];
// Add strings in an array.
console.log(
'Adding strings:',
arrayOne.reduce((acc, curr) => acc + curr)
);
// Add the values of each element together with an initial value.
const arrayTwo = ['b', 'c', 'd', 'e'];
console.log(
'Adding with initial value:',
arrayTwo.reduce((acc, curr) => acc + curr, 'a')
);

This will yield the following output:

Adding strings: abcde
Adding with initial value: abcde

Codebyte Example

The following example uses .reduce() to subtract numbers in an expenses array from the initial monthlyBudget provided:

Code
Output
Loading...

Contributors

Interested in helping build Docs? Read the Contribution Guide or share your thoughts in this feedback form.

Learn JavaScript on Codecademy