Loop over the array carrying an accumulator: start from the initial value, or from the first element when none is given, and replace the accumulator with callback(acc, element, index, array) each turn. The spec details are what's being tested: decide "no initial value" by the number of arguments, not by === undefined; with no initial value, start at the first element that exists and throw a TypeError on an empty array; skip holes; read length once; and throw if the callback isn't a function. reduceRight is the same walk backwards, and a pipeline of functions is just a reduce.
Implement a polyfill of Array.prototype.reduce.
Answer it out loud, in your own words. Then compare.
Interviewers listen for how you get there, not only where you land. The answer opens once you have tried.
Start from initialValue, or from this[0] and index 1 when it wasn't passed, and fold each element in. Checking arguments.length rather than initialValue === undefined matters: [1].reduce(fn, undefined) must start from undefined. reduce can build any shape, not just sums: here, a word count.
Array.prototype.myReduce = function (callback, initialValue) {let i = 0;let acc = initialValue;if (arguments.length < 2) {// No initial value: the first element is the start.acc = this[0];i = 1;}for (; i < this.length; i++) acc = callback(acc, this[i], i, this);return acc;};
passes 4 checks run on every build, against the native method where there is one
- sums with and without an initial value, like native
- builds objects: counting words
- passes index and the array
- an explicit undefined start is used
Without an initial value the start is the first index that exists (k in O), so [, , 7].reduce(fn) returns 7 without calling fn, and an empty or all-holes array throws TypeError: Reduce of empty array with no initial value. Holes are skipped during the walk too. length is read once, so pushing inside the callback doesn't extend the loop, and Object(this) lets it run on array-likes.
function toLength(value) {const n = Math.trunc(Number(value)) || 0;return Math.min(Math.max(n, 0), Number.MAX_SAFE_INTEGER);}Array.prototype.myReduce = function (callback, ...initial) {if (typeof callback !== 'function') throw new TypeError(`${String(callback)} is not a function`);const O = Object(this); // array-likes tooconst len = toLength(O.length); // read oncelet k = 0;let acc;if (initial.length > 0) acc = initial[0];else {while (k < len && !(k in O)) k++; // the first element that existsif (k >= len) throw new TypeError('Reduce of empty array with no initial value');acc = O[k++];}for (; k < len; k++) if (k in O) acc = callback(acc, O[k], k, O); // holes are skippedreturn acc;};
passes 4 checks run on every build, against the native method where there is one
- empty without a start throws a TypeError, like native
- skips holes and starts at the first element that exists
- length is read once
- array-likes and a missing callback
reduceRight is the mirror walk; the compose below uses it to apply functions right to left. An async reduce has to await the accumulator each turn, so each step starts after the previous one finishes; items.reduce(async (acc, x) => (await acc) + x) works too but is easy to get wrong. pipe(f, g)(x) is [f, g].reduce((v, fn) => fn(v), x): middleware, data transforms and Redux's compose are all reduces over functions.
function toLength(value) {const n = Math.trunc(Number(value)) || 0;return Math.min(Math.max(n, 0), Number.MAX_SAFE_INTEGER);}Array.prototype.myReduce = function (callback, ...initial) {if (typeof callback !== 'function') throw new TypeError(`${String(callback)} is not a function`);const O = Object(this); // array-likes tooconst len = toLength(O.length); // read oncelet k = 0;let acc;if (initial.length > 0) acc = initial[0];else {while (k < len && !(k in O)) k++; // the first element that existsif (k >= len) throw new TypeError('Reduce of empty array with no initial value');acc = O[k++];}for (; k < len; k++) if (k in O) acc = callback(acc, O[k], k, O); // holes are skippedreturn acc;};// The same walk from the end.Array.prototype.myReduceRight = function (callback, ...initial) {if (typeof callback !== 'function') throw new TypeError(`${String(callback)} is not a function`);const O = Object(this);let k = toLength(O.length) - 1;let acc;if (initial.length > 0) acc = initial[0];else {while (k >= 0 && !(k in O)) k--;if (k < 0) throw new TypeError('Reduce of empty array with no initial value');acc = O[k--];}for (; k >= 0; k--) if (k in O) acc = callback(acc, O[k], k, O);return acc;};// reduce over async steps: each waits for the previous result, in order.async function reduceAsync(items, callback, initial) {let acc = await initial;for (let i = 0; i < items.length; i++) acc = await callback(acc, items[i], i, items);return acc;}// A pipeline is a reduce over functions; compose is the same from the right.const pipe = (...fns) => (x) => fns.myReduce((v, f) => f(v), x);const compose = (...fns) => (x) => fns.myReduceRight((v, f) => f(v), x);
passes 3 checks run on every build, against the native method where there is one
- reduceRight walks from the end, like native
- reduceAsync runs steps in order, each after the previous
- pipe and compose are reduces over functions
Totals and lookups
Cart totals (items.reduce((sum, i) => sum + i.price * i.qty, 0)) and building an id → record lookup from a list are the everyday reduces. For grouping, Object.groupBy now does it directly.
Redux reducers
A Redux reducer is a function (state, action) => newState with the same shape as a reduce callback: the state is the accumulator, and replaying a list of actions is literally actions.reduce(reducer, initialState).
Composing middleware
Redux's compose turns a list of functions into one with a reduce ((a, b) => (...args) => a(b(...args))), the same idea as the function-pipeline stage.
Forgetting the initial value when reducing into an object: the first element becomes the accumulator.
Checking
initialValue === undefinedinstead of the argument count.Spreading the accumulator every turn (
{ ...acc, [k]: v }) on big arrays: that copies the object each time,O(n²)overall.Using reduce with
asynccallbacks without awaiting the accumulator.Returning nothing from the callback by accident, so the accumulator becomes
undefined.
When is a plain loop better than reduce?
When the reduce mutates something outside, needs to break early, or the accumulator is being copied each turn. A for...of loop is clearer and faster there.
How would you write map and filter with reduce?
map: arr.reduce((acc, x, i, a) => { acc.push(fn(x, i, a)); return acc; }, []); filter: push only when the predicate is truthy. Both drop holes where native map keeps them.
What does reduce return on a one-element array without an initial value?
That element, without calling the callback at all.