Flatten a Nested JavaScript Array

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]
asked …
LeaderboardSalaryAccount