Implement flatten(arr, depth = 1), which behaves like arr.flat(depth). Don't call Array.prototype.flat or flatMap.
It returns a new array in which nested arrays are unwrapped up to depth levels. Unwrapping means the items of a nested array take the place of the array itself.
depthdefaults to1.Infinityunwraps everything.0or a negative depth unwraps nothing and returns a shallow copy.- The order of items is kept. An empty nested array that gets unwrapped leaves nothing behind.
- Holes in sparse arrays (indexes never assigned, as in
[1, , 2]) are dropped in every array that gets unwrapped. Realundefinedandnullvalues are kept. - Don't modify the input.
Constraints: up to 200 000 items in total, and arrays may be nested up to 100 000 levels deep.
Input: flatten([1, [2, [3, [4]]], 5])
Output: [1, 2, [3, [4]], 5]
Input: flatten([1, [2, [3, [4]]]], 2)
Output: [1, 2, 3, [4]]
Input: flatten([[], ['a'], [[], 'b']], Infinity)
Output: ['a', 'b']