FrontendArk

Master Frontend Interviews

  • Practice
  • Playground
  • Resource
Medium

Flatten Array

20mins

You are given an array that may contain nested arrays at any depth.

// Examples of input arrays [1, 2, 3] [1, [2, 3]] [[1, 2], [3, 4]] [1, [2, [3, [4, [5]]]]]

Your task: Implement flatten(arr) which returns a new array with all nested elements flattened into a single level. The original array should not be modified.

Example

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

Code Editor

JavaScript Function

00:00
Loading...

Test Cases

No test results yet

Click "Run" to execute tests