Flatten Array
MediumP1Coding
Write flatten(arr, depth), which returns a new array with nested arrays flattened up to depth levels.
depth = 1flattens one level:[1,[2,[3]]]becomes[1,2,[3]].depth = 0returns a shallow copy with nothing flattened.- A negative
depthmeans 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
Give it a real attempt first. Run shows which examples fail.
Saved automatically
Run checks the 3 visible tests, Submit all 11. ⌘Enter runs, ⌘⇧Enter submits.