Skip to solution
easyDSA

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

779 views
01

Understand the problem

Create flat(arr, depth=1) that flattens nested arrays up to depth. Also implement flatMap.

arrayflatrecursion
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Approach: Recursive DFS, decrement depth; depth = Infinity fully flattens.

function flat(arr, depth = 1) {
  const res = [];
  (function helper(a, d) {
    for (const v of a) {
      if (Array.isArray(v) && d > 0) helper(v, d - 1);
      else res.push(v);
    }
  })(arr, depth);
  return res;
}
fun

Solution ready — 2 min read

Classified // press E to declassify

04

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 45 of 190 decoded in the JavaScript Coding track. One more won't hurt.

Back to track