The reduce() method executes a reducer function on each element of the array and returns a single output value.
Example
reduce() Syntax
The syntax of the reduce() method is:
arr.reduce(callback(accumulator, currentValue), initialValue)
Here, arr is an array.
reduce() Parameters
The reduce() method takes in:
- callback - The function to execute on each array element (except the first element if no initialValue is provided). It takes in
- accumulator - It accumulates the callback's return values.
- currentValue - The current element being passed from the array.
- initialValue (optional) - A value that will be passed to
callback()on first call. If not provided, the first element acts as the accumulator on the first call andcallback()won't execute on it.
Note: Calling reduce() on an empty array without initialValue will throw TypeError.
reduce() Return Value
- Returns the single value resulting after reducing the array.
Notes:
reduce()executes the given function for each value from left to right.reduce()does not change the original array.- It is almost always safer to provide
initialValue.
Example 1: Sum of All Values of Array
Output
21 21
Example 2: Subtracting Numbers in Array
Output
1330 2700
This example clearly explains the difference between passing an initialValue and not passing an initialValue.
Example 3: Remove Duplicate Items from Array
Output
[ 18, 21, 1, 51, 5, 7, 10 ]
Example 4: Grouping Objects by a property
Output
{
'19': [ { name: 'Dwight', age: 19 } ],
'21': [ { name: 'John', age: 21 }, { name: 'Oscar', age: 21 } ],
'55': [
{ name: 'Oliver', age: 55 },
{ name: 'Michael', age: 55 },
{ name: 'Kevin', age: 55 }
]
}
Recommended Reading: JavaScript Array reduceRight()