FrontendPro

8Implement a function to flatten a nested array

easyAbout 15 minutesCodingarraysrecursion

Problem

Implement flatten(array, depth = Infinity). It returns a new array with nested arrays flattened into it, up to depth levels, like Array.prototype.flat(). Do not use flat() itself.

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

Requirements

  • Without depth, flatten completely.
  • depth = 0 returns a shallow copy.
  • Do not change the input.
  • Skip holes in sparse arrays, like flat() does.
  • Only arrays are flattened: strings and array-like objects stay as they are.

Try it yourself

Write your solution, run it, then submit to check it against the tests.

solution.jsJavaScript

Press Run or ⌘ Enter to execute your code.

Video walkthroughs

Stuck? Watch someone solve it, then try again on your own.

Writing polyfill for Array.flat() method in JavaScript | Flatten a deeply nested array in JSAnkit Saxena on YouTubeOpen on YouTube
Deep Flatten I (Arrays) - Frontend Interview QuestionShivam Bhalla on YouTubeOpen on YouTube

Step-by-step

Push every value into a single result array. Building and concatenating new arrays at every level costs extra copies.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 3 code listings, 5 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever