Skip to content
jshacks.dev
Functions

Implement Array.prototype.flat From Scratch in JavaScript

Implement Array.prototype.flat from scratch in JavaScript with depth, Infinity, holes and a stack-based version for deep input, and compare it with flatMap.

7 min read
Summarize in AI
Flat illustration of items passing through a chain of collection methods, with the JavaScript, TypeScript, Node.js, Vite and npm logos.

Array.prototype.flat(depth) returns a new array in which nested arrays are unwrapped up to depth levels. The question is popular because the recursive answer is natural, and the details that follow are the real test: the default depth is one and not infinity, Infinity must work, holes are removed, only real arrays are flattened and not array-likes, and a very deep nesting can overflow the stack. This post implements flat on Node.js 24 step by step, shows the output of each case and ends with an iterative version that has no depth limit, the relation to flatMap and tests. For flattening objects, which is a different problem, see flattening deeply nested data with recursion.

The behavior to match

JavaScript
const nested = [1, [2, [3, [4]]], 5];

console.log(nested.flat());
console.log(nested.flat(2));
console.log(nested.flat(Infinity));
console.log(nested.flat(0));
Text
[ 1, 2, [ 3, [ 4 ] ], 5 ]
[ 1, 2, 3, [ 4 ], 5 ]
[ 1, 2, 3, 4, 5 ]
[ 1, [ 2, [ 3, [Array] ] ], 5 ]

The default depth is 1, so only the outer level of nesting is removed. A depth of 0 copies the array without unwrapping anything, and Infinity goes all the way down. The last line shows Node.js shortening a deeply nested array as [Array] in its printout, which is a display detail and not a change to the data.

The recursive version

JavaScript
Array.prototype.myFlat = function (depth = 1) {
  const result = [];

  for (const item of this) {
    if (Array.isArray(item) && depth > 0) {
      result.push(...item.myFlat(depth - 1));
    } else {
      result.push(item);
    }
  }

  return result;
};

console.log(nested.myFlat());
console.log(nested.myFlat(2));
console.log(nested.myFlat(Infinity));
console.log(nested.myFlat(0));
Text
[ 1, 2, [ 3, [ 4 ] ], 5 ]
[ 1, 2, 3, [ 4 ], 5 ]
[ 1, 2, 3, 4, 5 ]
[ 1, [ 2, [ 3, [Array] ] ], 5 ]

The recursion reduces the depth by one on each level, and stops unwrapping when depth reaches zero. For Infinity, Infinity - 1 is still Infinity, so the recursion never stops reducing and relies on the data running out of arrays. That works because each level of the data is finite. The identical output on all four lines is the test.

There are two issues in this version. The first is the default parameter: flat(undefined) should use the default depth of 1, and it does. But flat(null) converts null to 0 in the real method, and with the code above depth > 0 is false for null, which also gives zero unwrapping. The real method converts the argument to an integer first, so flat("2") is flat(2). A faithful version normalizes the depth.

JavaScript
function toDepth(value) {
  const number = Number(value);

  if (Number.isNaN(number)) {
    return 0;
  }

  return Math.trunc(number);
}

console.log(toDepth("2"), toDepth(null), toDepth(1.9), toDepth("x"), toDepth(-1), toDepth(Infinity));
Text
2 0 1 0 -1 Infinity

Number("2") is 2, Number(null) is 0, 1.9 truncates to 1, text that is not a number becomes NaN and then 0, and a negative depth stays negative, so it unwraps nothing. Math.trunc(Infinity) is Infinity. Only undefined gets the default of 1, which the parameter default handles.

Holes are removed

flat drops empty slots from the arrays it visits, including nested ones.

JavaScript
const sparse = [1, , [2, , 3], , 4];

console.log(sparse.flat());
console.log(sparse.myFlat());
Text
[ 1, 2, 3, 4 ]
[ 1, undefined, 2, undefined, 3, undefined, 4 ]

The real method skips missing indexes. A for...of loop does not, because the array iterator reads every index and yields undefined for a hole. To skip holes, loop with an index and test i in array.

JavaScript
function flatten(array, depth = 1) {
  const result = [];

  for (let i = 0; i < array.length; i += 1) {
    if (!(i in array)) {
      continue;
    }

    const item = array[i];

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

  return result;
}

console.log(flatten(sparse, 2));
Text
[ 1, 2, 3, 4 ]

The result matches the built-in. This is the one place where for...of is the wrong loop, and a reader may not know why, so a comment helps.

Only arrays are flattened

Array-like objects and iterables other than arrays are kept as items.

JavaScript
const mixed = [new Set([1, 2]), "ab", { length: 1, 0: "x" }, [3]];

console.log(mixed.flat());
Text
[ Set(2) { 1, 2 }, 'ab', { '0': 'x', length: 1 }, 3 ]

Only the real array [3] was unwrapped. The Set, the string and the array-like object stay as they are, and the real method uses Array.isArray for this decision, which is also what the code above uses. A check with item instanceof Array would fail for arrays from another realm, such as an iframe, and Array.isArray handles them.

The stack problem and an iterative version

The recursive function adds a stack frame for each level of nesting, and push(...item) also places every element of a flattened subarray on the stack as an argument. Deep nesting or a huge inner array can throw a RangeError.

JavaScript
let deep = [1];

for (let i = 0; i < 200_000; i += 1) {
  deep = [deep];
}

try {
  flatten(deep, Infinity);
} catch (error) {
  console.log(error.name);
}
Text
RangeError

Two hundred thousand levels is far deeper than real data, and it is the sort of input an attacker can send as JSON. An explicit stack gives a version with no depth limit.

JavaScript
function flatIterative(array, depth = 1) {
  const result = [];
  const stack = [[array, 0, depth]];

  while (stack.length > 0) {
    const frame = stack[stack.length - 1];
    const [current, index, remaining] = frame;

    if (index >= current.length) {
      stack.pop();
      continue;
    }

    frame[1] += 1;

    if (!(index in current)) {
      continue;
    }

    const item = current[index];

    if (Array.isArray(item) && remaining > 0) {
      stack.push([item, 0, remaining - 1]);
    } else {
      result.push(item);
    }
  }

  return result;
}

console.log(flatIterative(sparse, 2));
console.log(flatIterative(deep, Infinity));
Text
[ 1, 2, 3, 4 ]
[ 1 ]

Each stack entry holds an array, the next index to read and the remaining depth. The loop reads one element at a time from the top array. A nested array that is within the depth gets a new frame, and anything else is appended to the result. The frame is popped when its array is exhausted. The call stack stays flat, and a nesting of two hundred thousand levels finishes and returns [1]. The cost is code that is harder to read, so use it only where depth comes from untrusted data.

Relation to flatMap

flatMap(fn) is map(fn) followed by flat(1), in a single pass. It is the right tool when each element becomes zero, one or many elements.

JavaScript
const sentences = ["a b", "", "c d e"];

console.log(sentences.map((s) => s.split(" ")).flat());
console.log(sentences.flatMap((s) => (s ? s.split(" ") : [])));
Text
[ 'a', 'b', '', 'c', 'd', 'e' ]
[ 'a', 'b', 'c', 'd', 'e' ]

The first line keeps an empty string, because "".split(" ") returns [""]. The second uses flatMap to return an empty array for empty input, which both filters and maps in one step. flatMap only flattens one level, so a callback returning an array of arrays stays nested at the second level.

Tests

JavaScript
import test from "node:test";
import assert from "node:assert/strict";

test("flat respects depth", () => {
  assert.deepEqual([1, [2, [3]]].myFlat(), [1, 2, [3]]);
  assert.deepEqual([1, [2, [3]]].myFlat(Infinity), [1, 2, 3]);
  assert.deepEqual([1, [2, [3]]].myFlat(0), [1, [2, [3]]]);
});

test("flatten removes holes", () => {
  assert.deepEqual(flatten([1, , [2, , 3]], 1), [1, 2, 3]);
});
Text
ℹ tests 2
ℹ pass 2
ℹ fail 0

Choosing between the versions

In application code you will use the built-in flat and never write any of this. The three implementations exist to show three different trade-offs. The simple recursive one is the clearest and is correct for data that you control, such as a configuration you wrote or a list of categories. The shared-result recursive one is the same idea without copying, and it is the one to keep if you need a custom variant, for example a flatten that also tracks the path of each item. The stack-based one is for input from outside, where somebody else decides how deep the nesting goes.

Whichever you pick, test the same four things: the default depth, Infinity, a hole in the middle and an empty nested array. Those cases catch nearly every mistake in this family of functions.

How to present it

Write the recursive version in a few lines. Before the interviewer asks, mention the default depth of one, because it is the most common mistake: people expect a full flatten. Then handle Infinity explicitly, noting that the recursion reaches it naturally. Next bring up holes and the loop that skips them, and finish with the stack depth issue and the iterative version. Being able to say "the recursive version is correct for any realistic data, and this is what I would do for untrusted input" is a strong close.

If the interviewer asks for the cost, say that each element is visited once, so the time is linear in the total number of elements across all levels, and the extra memory is the result plus the stack depth. With push(...item) the intermediate arrays copy elements once per level, which can make deeply nested data quadratic in the worst case, and a single shared result passed down the recursion avoids that.

JavaScript
function flatShared(array, depth, result = []) {
  for (let i = 0; i < array.length; i += 1) {
    if (!(i in array)) continue;

    const item = array[i];

    if (Array.isArray(item) && depth > 0) {
      flatShared(item, depth - 1, result);
    } else {
      result.push(item);
    }
  }

  return result;
}

console.log(flatShared([1, [2, [3, [4]]]], Infinity));
Text
[ 1, 2, 3, 4 ]

Passing the output array down avoids both the intermediate arrays and the spread, at no cost in readability.

Taggedinterview
Share

Keep reading

Flat illustration of two options weighed side by side, with the JavaScript, Vite and Node.js logos.
Functions

Classes vs Factory Functions

Classes vs factory functions in JavaScript compared on private state, this, instanceof, inheritance, memory, JSON and testing, with exact output.

7 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.