6. Implement flatten(arr, depth) — Flatten a Nested Array

easy

A warm-up question that checks whether you reach for recursion cleanly and remember that flat() takes a depth.

The idea

reduce builds a new array; for each element decide: is it a nested array with depth remaining? Recurse. Otherwise keep it.

Follow-ups

  • "Without recursion?" → use an explicit stack (shown in the Solution tab).
  • "Why not just arr.flat(Infinity)?" → that's the real-world answer; the interviewer wants the algorithm behind it.
  • "Huge, deeply nested input?" → recursion risks a stack overflow; prefer the iterative version.

What to practice

Write the recursive version, then the stack-based one, and be ready to say which you'd ship and why.

More questions

index.js
function flatten(arr, depth = Infinity) {
  // your code here
}

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

Tests

Test Code

Enter JavaScript that runs after your solution. It should return a value or a Promise.