JavaScript Reduce
reduce() folds an array into a single value: the callback receives an accumulator and the current element, and whatever it returns becomes the accumulator for the next round. The optional initial value seeds the accumulator.
Syntax
arr.reduce((acc, x) => acc + x, 0) Examples
| Input | Arguments | Output |
|---|---|---|
| [1, 2, 3] | (acc, x) => acc + x, 0 | 6 |
| ["b", "c"] | (acc, x) => acc + x, 'a' | "abc" |
| ↳ The seed can be a string: reduce can build any type of result. | ||
When to use it
- Sum, average or count the elements of a list.
- Build a string, object or new array from a list in one pass.
Gotchas
- Reducing an empty array without an initial value throws a TypeError in native JavaScript. Always provide a seed.
- The accumulator can be any type: number, string, object or array.
Try it live
Type your input and see Reduce transform it instantly.
Want to go further? Chain Reduce with other functions, pipe one output into the next and watch your data transform in the visual Playground.