← Back to JavaScript, page 5

javascript-0083 · Medium mid

How would you implement Array.prototype.map, reduce, and flat yourself? What details must a correct version handle?

A correct polyfill follows the specification details: callbacks receive (value, index, array), a thisArg is respected, holes in sparse arrays are skipped, reduce without an initial value uses the first existing item and throws on an empty array, and flat takes a depth and recurses only for nested arrays. Writing them shows how the built-in methods really behave.

Full answer

Interviewers ask for these implementations to see whether a candidate knows the real behavior of the methods, not only the happy path.

For map, the method creates a result array with the same length, and for every index that exists, it calls callback.call(thisArg, value, index, array) and stores the result. Indexes that are holes in a sparse array are skipped, so the result keeps the holes. It should throw a TypeError if the callback is not a function.

For reduce, the accumulator starts as the initial value if one was given (check arguments.length or the rest parameter length, not undefined, because undefined can be a valid initial value). Without an initial value, the first existing item is used as the accumulator and the loop starts after it. On an empty array with no initial value, it throws a TypeError. The callback receives (accumulator, value, index, array).

For flat(depth = 1), walk the items and for each array item, flatten it with depth - 1, otherwise push the item. A depth of 0 copies the array shallowly, and Infinity flattens everything. Holes are removed. A recursive version is short, while an iterative version with an explicit stack avoids stack overflow on very deep arrays.

Another detail is that the real methods read length once at the start, so items appended during iteration are not visited. Define the polyfills with Object.defineProperty so they are not enumerable, otherwise for...in over arrays would show them. Only add a polyfill when the method does not already exist.

javascript
function myMap(callback, thisArg) {
  if (typeof callback !== 'function') throw new TypeError(`${callback} is not a function`);
  const source = this;
  const length = source.length;
  const result = new Array(length);
  for (let i = 0; i < length; i++) {
    if (i in source) result[i] = callback.call(thisArg, source[i], i, source);
  }
  return result;
}

function myReduce(callback, ...initial) {
  if (typeof callback !== 'function') throw new TypeError(`${callback} is not a function`);
  const source = this;
  const length = source.length;
  let index = 0;
  let accumulator;
  if (initial.length > 0) {
    accumulator = initial[0];
  } else {
    while (index < length && !(index in source)) index++;
    if (index >= length) throw new TypeError('Reduce of empty array with no initial value');
    accumulator = source[index++];
  }
  for (; index < length; index++) {
    if (index in source) accumulator = callback(accumulator, source[index], index, source);
  }
  return accumulator;
}

function myFlat(depth = 1) {
  const result = [];
  const walk = (list, remaining) => {
    for (let i = 0; i < list.length; i++) {
      if (!(i in list)) continue;
      if (Array.isArray(list[i]) && remaining > 0) walk(list[i], remaining - 1);
      else result.push(list[i]);
    }
  };
  walk(this, depth);
  return result;
}

const methods = { myMap, myReduce, myFlat };
for (const [name, fn] of Object.entries(methods)) {
  Object.defineProperty(Array.prototype, name, { value: fn, writable: true, configurable: true, enumerable: false });
}

console.log([1, 2, 3].myMap((x) => x * 2), [1, 2, 3].map((x) => x * 2));
const sparse = [1, , 3];
console.log(sparse.myMap((x) => x + 1), sparse.map((x) => x + 1));
console.log([1, 2].myMap(function (x) { return x * this.factor; }, { factor: 10 }));

console.log([1, 2, 3, 4].myReduce((a, b) => a + b), [1, 2, 3, 4].myReduce((a, b) => a + b, 10));
console.log([].myReduce((a, b) => a + b, 'start'), [undefined].myReduce((a) => a, 'x'));
try {
  [].myReduce((a, b) => a + b);
} catch (error) {
  console.log(error.name + ': ' + error.message);
}
console.log([1, , 3].myReduce((a, b) => a + b));

const nested = [1, [2, [3, [4]]], , 5];
console.log(nested.myFlat(), nested.flat());
console.log(nested.myFlat(2), nested.flat(2));
console.log(nested.myFlat(Infinity), nested.myFlat(0));

const keys = [];
for (const key in [1]) keys.push(key);
console.log('enumerable keys on an array:', keys);

Run with Node.js v24.22.1 as js-83.js; two runs gave identical output. Output: [ 2, 4, 6 ] [ 2, 4, 6 ] [ 2, <1 empty item>, 4 ] [ 2, <1 empty item>, 4 ] [ 10, 20 ] 10 20 start x TypeError: Reduce of empty array with no initial value 4 [ 1, 2, [ 3, [ 4 ] ], 5 ] [ 1, 2, [ 3, [ 4 ] ], 5 ] [ 1, 2, 3, [ 4 ], 5 ] [ 1, 2, 3, [ 4 ], 5 ] [ 1, 2, 3, 4, 5 ] [ 1, [ 2, [ 3, [Array] ] ], 5 ] enumerable keys on an array: [ '0' ]

Key points

  • Callbacks get (value, index, array) and respect thisArg; reject non-functions with TypeError.
  • Skip holes in sparse arrays; keep length fixed at the start.
  • reduce: use the first existing item when no initial value; throw on empty input.
  • flat: depth defaults to 1; recurse only for arrays; Infinity flattens fully.
  • Define polyfills as non-enumerable and only if missing.

Common mistakes

  • Checking initialValue === undefined instead of how many arguments were passed.
  • Forgetting to skip holes, which makes sparse arrays behave differently from the built-ins.
  • Defining the method with plain assignment, which makes it enumerable and visible in for...in.
  • Flattening with recursion for any depth and not respecting the depth argument.

Follow-ups

  • How would you write an iterative flat that avoids stack overflow?
  • How would you implement filter and forEach with the same care?
  • Why does the specification read length once at the start?

Tips

  • State the edge cases before coding: holes, thisArg, empty reduce, and depth.
  • Use `i in source` to skip holes; it shows you know sparse arrays.
  • Mention defineProperty and non-enumerable methods when asked about polyfills.