Anonymous contributor's avatar
Anonymous contributor
Anonymous contributor's avatar
Anonymous contributor
Published Jun 22, 2021Updated Nov 25, 2022
Contribute to Docs

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


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.


const arrayOne = ['a', 'b', 'c', 'd', 'e'];
// Add strings in an array.
'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'];
'Adding with initial value:',
arrayTwo.reduce((acc, curr) => acc + curr, 'a')
// Add the values of each object inside an array.
const arrayThree = [{ x: 1 }, { x: 2 }, { x: 4 }];
'Adding object values:',
arrayThree.reduce((acc, curr) => acc + curr.x, 0)

This will yield the following output:

Adding strings: abcde
Adding with initial value: abcde
Adding object values: 7

Codebyte Example

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

Visit us
Hide code
Hide output
Hide output

All contributors

Looking to contribute?

Learn JavaScript on Codecademy