JavaScript Reference ยท Array
Array.prototype.reduce()
Reference for JavaScript Array.prototype.reduce(): fold an array into one value with an accumulator, the initial value, empty-array errors and common patterns.
The reduce() method walks through an array from left to right, passing a running result (the accumulator) and the current element to your function. Whatever the function returns becomes the accumulator for the next step. After the last element, reduce() returns the final accumulator.
It can build sums, maximums, lookup objects, grouped data or even a new array. Because it is so general, simpler methods such as map(), filter() and some() are often clearer when they fit.
const total = [1, 2, 3, 4].reduce((sum, n) => sum + n, 0); // 10
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
array.reduce(callbackFn) array.reduce(callbackFn, initialValue)
| Name | Description |
|---|---|
callbackFn |
Called as callbackFn(accumulator, currentValue, currentIndex, array). Its return value becomes the next accumulator. |
initialValue |
Optional. The accumulator for the first call. If you omit it, the first element is the starting accumulator and iteration begins at the second element. |
Return value: the final accumulator value.
Exceptions: a TypeError if callbackFn is not a function, or if the array is empty and no initialValue was given.
Usage notes
- Always pass an initial value unless you are sure the array is not empty and the element type matches the result type. It avoids the empty-array
TypeErrorand makes the result type obvious. - Single element, no initial value: the callback is never called and that element is returned. An empty array with an initial value also returns the initial value without calling the callback.
- You must
returnthe accumulator in every branch. Forgetting it makes the next step seeundefined. - It does not mutate the array, but the callback can mutate the accumulator. Reusing and mutating one object is fast; creating a new object every step (
{ ...acc, [k]: v }) is easy to read but gets slow, because the work grows quadratically with the number of entries. - Holes are skipped. Empty slots in sparse arrays are not visited.
- Readability. A long
reduce()is often clearer as afor...ofloop. Reach forreduce()when the result is naturally a fold. - Direction: use
reduceRight()to go from the last element to the first. - Async work:
reduce()does not wait for promises. Chain them explicitly (acc.then(...)) or use afor...ofloop withawait. - Grouping: for grouping by key,
Object.groupBy()orMap.groupBy()are shorter where available.
Browser support
Array.prototype.reduce() is part of ES5 and works in every browser in use today.