Flatten array, depth-controlled
15 min·senior·recursion · arrays
Implement flatten(arr, depth = 1) matching Array.prototype.flat:
flatten([1, [2, [3, [4]]]]) // [1, 2, [3, [4]]] flatten([1, [2, [3, [4]]]], 2) // [1, 2, 3, [4]] flatten([1, [2, [3, [4]]]], Infinity) // [1, 2, 3, 4]
Bonus: iterative version for deep arrays (avoid stack overflow).
expected time · O(n)
expected space · O(d) recursion or O(n) stack
4 lines
⏵ run · no run yet · ctrl+enter