FrontendInterviews.dev

Loading problem…

41. Flatten Nested Arrays to Single Level

Medium•
Acceptance: 77.78%
•
🔓3/3 Pro unlocks today

Implement a function that flattens a deeply nested array structure into a single-level array.

Requirements

Your function should:

  • Handle arrays nested to any depth
  • Preserve the order of elements
  • Handle non-array values correctly
  • Work with mixed types (numbers, strings, objects, etc.)

Example

flatten([1, [2, [3, [4]], 5]])
// Output: [1, 2, 3, 4, 5]

flatten([[1, 2], [3, 4], [5]])
// Output: [1, 2, 3, 4, 5]

flatten([1, [], [2, [[[3]]]]])
// Output: [1, 2, 3]

Constraints

  • Do not use Array.prototype.flat()
  • Preserve left-to-right element order in the flattened result.
  • Handle empty input arrays correctly.
  • Support arbitrary nesting depth for standard nested arrays.