Array.prototype.reduce
Reduces an array to a single value.
Available since: ES5
Syntax
array.reduce(callbackFn, initialValue)Parameters
| Parameter | Type | Description |
|---|---|---|
| callbackFn | Function | A function that receives the accumulated value and the next element and returns the new accumulated value. |
| initialValue | any | The initial accumulated value. |
Return value
anyThe final accumulated value.
Examples
Sum of numbers:
console.log([1, 2, 3, 4].reduce((sum, n) => sum + n, 0));Output:
10Summing a property of objects:
const orders = [{ total: 100 }, { total: 250 }];
console.log(orders.reduce((sum, order) => sum + order.total, 0));Output:
350Notes
Always pass an initial value: without it, calling the method on an empty array throws an error.
See also
- Array.prototype.map — Creates a new array by transforming every element.
- Array.prototype.forEach — Runs a function for every element of an array.
- Array.prototype.reduceRight — Reduces an array to one value, going from right to left.
- Object.groupBy — Groups the elements of an array by a key.
Related recipes
In the tutorial
- map, filter and reduce — The three main array processing methods in JavaScript: transforming, selecting and reducing to a single value.