Turning Learners Into Developers
Codekilla
CODEKILLA
Medium
JS-003javascript

Flatten Nested Array to Depth N

Problem

Implement `flat(arr, depth)` without using the built-in `Array.prototype.flat`.

Input
N/A — run a test case and print the result.
Output
JSON.stringify of the flattened result.
Constraints
depth ≥ 0, input is an array that may contain arrays at any depth.
Sample input
[1, [2, [3, [4]]]], depth=2
Sample output
[1,2,3,[4]]
Explanation
Depth-2 flatten unwraps the first two levels of nesting.
recursionarraysfunctional@Google@Meta
Visible test cases
in: [1, [2, [3, [4]]]], depth=1
out: [1,2,[3,[4]]]
in: [1, [2, [3, [4]]]], depth=Infinity
out: [1,2,3,4]
Your solution — run it, use AI if stuck
javascript