Array.prototype.reduce()
Reduces the array to a single value by applying an accumulator function left to right.
Syntax
arr.reduce(callback, initialValue) Parameters
| Name | Type | Required | Description |
|---|---|---|---|
callback | Function | Yes | Reducer called with (accumulator, currentValue, index, array). Its return value becomes the next accumulator. |
initialValue | any | No | Starting value for the accumulator. If omitted, the first element is used and iteration starts at index 1. |
Returns
any — The single value resulting from the reduction.
Throws
TypeError— the array is empty and no initialValue is provided.
Examples
const nums = [1, 2, 3, 4];
console.log(nums.reduce((sum, n) => sum + n, 0));
Output
10
const items = ['a', 'b', 'a', 'c', 'a'];
const counts = items.reduce((acc, k) => {
acc[k] = (acc[k] || 0) + 1;
return acc;
}, {});
console.log(counts);
Output
{ a: 3, b: 1, c: 1 }
Notes
Always supply an initialValue to avoid the empty-array TypeError and to make
intent clear. Use `reduceRight` to iterate from the end. Does not mutate the array.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 3.0 |
| firefox | 3.0 |
| safari | 4.0 |
| edge | 12 |
| node | 0.10 |