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

← All JS array methods · TypeScript vs JavaScript