Skip to main content

Search

Search problems, hooks, and pages

Flatten Nested Array

Write a function that takes a deeply nested array and returns a flat (one-dimensional) array containing all the values. The function should optionally accept a depth parameter — if given, flatten only up to that many levels. This tests recursion, array manipulation, and knowledge of modern JS APIs.

Examples

Input: [1, [2, [3, [4]], 5]]
Output: [1, 2, 3, 4, 5]
// All levels flattened (default: Infinity depth).
Input: [1, [2, [3, [4]]]] with depth = 1
Output: [1, 2, [3, [4]]]
// Only the first level is flattened.
Input: [] (empty)
Output: []

Constraints

  • Elements can be numbers, strings, or nested arrays.
  • depth parameter (optional) limits how many levels to flatten; Infinity flattens all.
  • Should not mutate the original array.
arrayrecursionstackes6reduce

Important

Interview Tip

Start by mentioning Array.prototype.flat(Infinity) to show you know the built-in. Then implement manually — the recursive approach is clearest and most interview-friendly. If asked about deeply nested arrays (stack overflow risk), present the iterative stack solution.

Approach: Brute Force

Repeatedly flatten one level at a time using concat spread, looping with Array.some(Array.isArray) until no nested arrays remain. Simple to explain but creates many intermediate arrays.

Complexity

Time: O(n × d)Space: O(n × d)

Pros

  • Very simple to explain
  • No recursion needed

Cons

  • Creates O(d) intermediate arrays — slow for deep nesting
  • Does not support depth parameter easily