Implement Array.prototype.flat with Depth Parameter
Problem Statement
Implement a function `flatten(arr, depth = 1)` that flattens nested arrays recursively up to the specified depth limit without using native `Array.prototype.flat()`.
Target Complexity
Time:
O(N) where N is total items in all sub-arrays
Space:
O(D) call stack depth
Interview Talking Points:
- • Explain recursive vs iterative stack-based approaches to avoid call stack overflow on 10,000+ nested arrays.
- • Discuss Array.prototype.reduce vs for...of loop performance in V8.
Solution Editor (JavaScript)
Ready to run
Test Results
Flattens 1 level by default
Test #1Flattens all levels with Infinity depth
Test #2