iteration
Array.prototype.reduce
Runs a reducer function on each element, left-to-right, folding the array into a single accumulated value. Reach for it to sum/product/group/build an object or any custom fold.
arr.reduce(callbackFn, initialValue?) Parameters
| Parameter | Purpose |
|---|---|
| callbackFn(acc, element, index, array) | Reducer — returns the next accumulator |
| initialValue | Starting accumulator; if omitted, arr[0] is used and iteration starts at index 1 |
Examples
console.log([1,2,3,4].reduce((a, n) => a + n, 0)); Logs: 10
console.log(['a','b','a','c','b','a'].reduce((m, w) => (m[w] = (m[w]||0)+1, m), {})); Logs: {a: 3, b: 2, c: 1}
console.log([[1,2],[3,4],[5]].reduce((a, b) => a.concat(b), [])); Logs: [1, 2, 3, 4, 5]
try { [].reduce((a, b) => a + b); } catch (e) { console.log(e.message); } Logs a TypeError: reduce of empty array with no initial value
Gotcha
Omitting initialValue on an empty array throws TypeError. Always pass an initialValue when the result type differs from the element type (e.g. building an object from strings).
Related methods
Array.prototype.map
Creates a new array populated with the results of calling a callback on every element of the calling array. Reach for it whenever you want to transform each element 1-to-1 into a new value.
Array.prototype.filter
Creates a new array containing every element for which the callback returned a truthy value. Reach for it to pare a list down to items matching a predicate.
Array.prototype.flatMap
Maps each element with a callback, then flattens the result by one level (ES2019). Reach for it when a mapper naturally returns arrays and you want a single flat list back.
Array.prototype.forEach
Executes a provided callback once for each array element, in ascending order. Reach for it when you need side effects (logging, DOM updates, pushing to another store) and do not need a return value.
Array.prototype.some
Returns true if the callback returns truthy for at least one element, short-circuiting on the first hit. Reach for it to answer "does anything match?" without walking the full array.