.reduce()
robgmerrill124 total contributions
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.
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 thecurrentValue
.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'));// Add the values of each object inside an array.const arrayThree = [{ x: 1 }, { x: 2 }, { x: 4 }];console.log('Adding object values:',arrayThree.reduce((acc, curr) => acc + curr.x, 0));
This will yield the following output:
Adding strings: abcdeAdding with initial value: abcdeAdding object values: 7
Codebyte Example
The following example uses .reduce()
to subtract numbers in an expenses
array from the initial monthlyBudget
provided:
All contributors
- robgmerrill124 total contributions
- Anonymous contributorAnonymous contributor1 total contribution
- BrandonDusch580 total contributions
- christian.dinh2476 total contributions
- Anonymous contributorAnonymous contributor3071 total contributions
- robgmerrill
- Anonymous contributor
- BrandonDusch
- christian.dinh
- Anonymous contributor
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.