Q10: Implement a polyfill for Array.prototype.flat().

Difficulty:IntermediateTopic:Recursion

Answer

The flat() method creates a new array with nested arrays flattened to a specified depth. Its default depth is 1.

Array.prototype.myFlat = function (depth = 1) {
  if (this == null) {
    throw new TypeError("Array.prototype.myFlat called on null or undefined");
  }

  const array = Object(this);
  const result = [];
  const maxDepth = Math.floor(Number(depth));
  const actualDepth = Number.isNaN(maxDepth)
    ? 0
    : Math.max(maxDepth, 0);

  function flatten(items, remainingDepth) {
    for (let i = 0; i < items.length; i++) {
      if (!(i in items)) {
        continue;
      }

      const value = items[i];

      if (Array.isArray(value) && remainingDepth > 0) {
        flatten(value, remainingDepth - 1);
      } else {
        result.push(value);
      }
    }
  }

  flatten(array, actualDepth);
  return result;
};

console.log([1, [2, [3, [4]]]].myFlat(2));
// [1, 2, 3, [4]]

Explanation

The recursive function traverses nested arrays while the remaining depth is greater than zero. It appends non-array values and arrays encountered at the requested depth to the result.

This is an interview-oriented implementation. Native flat() has more detailed coercion rules for depth and supports generic array-like receivers.

Key Takeaways
  • Flat recursively processes nested arrays up to the requested depth.
  • Sparse slots in flattened arrays are skipped.