2dbi

Flatten a Nested JavaScript Array

viaLeetCode

Problem Implement flatten(arr) in JavaScript: turn an arbitrarily nested array into a single-level array, preserving element order at any depth.

Input / Output

  • Input: nested array, e.g. [1, [2, [3, [4]], 5]].
  • Output: flat array [1, 2, 3, 4, 5].

Constraints

  • Arbitrary depth — deep recursion may overflow the stack for pathological inputs; discuss the iterative alternative. No Array.prototype.flat(Infinity) as the primary answer (implement it yourself).

Example

  • flatten([1, [2, [3, [4]], 5]]) → [1, 2, 3, 4, 5]
  • flatten([[], [[]], 1]) → [1]

Expected approach

  • Recursive: reduce over elements, concat flatten(el) when Array.isArray(el), else push — O(n) over total elements. Iterative: a stack, popping elements and pushing array contents back (mind order reversal). Follow-on talking points: generators (function* flattenGen) for lazy flattening, depth-limited flatten(arr, d) matching the native flat() signature, and handling sparse arrays/holes.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account