Skip to the solution
EasyDSA6 min read

Implement Array.prototype.flat() — flatten with depth

779 views

The problem

Problem, as an interviewer would state it: "Implement Array.prototype.myFlat(depth) from scratch — recursively flattening nested arrays up to the given depth, matching real native flat's own documented contract, including its default depth of 1."

Examples:

Code
[1, [2, 3], [4, [5, 6]]].myFlat();  // [1, 2, 3, 4, [5, 6]] -- default depth 1
[1, [2, 3], [4, [5, 6]]].myFlat(2); // [1, 2, 3, 4, 5, 6]

Clarifying questions expected:

  • What is the real, correct default depth when no argument is passed?
  • Should Infinity be a genuinely valid depth argument, flattening completely regardless of nesting?
  • Does flat() also remove real holes in a sparse array, at every flattened level?

Code / implementation expected: Yes — real, direct proof against the ACTUAL native flat, at the default depth, an explicit depth of 2, and Infinity, confirming identical output in every case.

  • array
  • flat
  • recursion

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

6 min read · 9 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

JavaScriptReal, direct proof: the flat polyfill matches real native flat at the default depth, an explicit depth of 2, and Infinity, including hole-removal on a sparse array

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 29 of 154 in JavaScript coding

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

Implement once(func) — ensure a function runs only once

Continue