Skip to content
Onsite

Flatten Array

MediumP1Coding

Write flatten(arr, depth), which returns a new array with nested arrays flattened up to depth levels.

  • depth = 1 flattens one level: [1,[2,[3]]] becomes [1,2,[3]].
  • depth = 0 returns a shallow copy with nothing flattened.
  • A negative depth means flatten completely, however deep.

The input contains only JSON values (numbers, strings, booleans, null and arrays). Keep non-array elements, including null, in their original order. Do not use the built-in Array.prototype.flat, and do not modify the input.

Example 1

Input
arr = [1,[2,[3,[4]]]], depth = -1
Output
[1,2,3,4]

Example 2

Input
arr = [1,[2,[3,[4]]]], depth = 1
Output
[1,2,[3,[4]]]

Example 3

Input
arr = [[],[[]]], depth = -1
Output
[]

Constraints

  • 0 <= total number of elements <= 10^4
  • Nesting depth is at most 1000.
  • -1 <= depth <= 1000 (any negative value means unlimited)

Hints

Run checks the 3 visible tests, Submit all 11.