Problem
Implement flatten(arr, depth = Infinity) — your own version of Array.prototype.flat.
Nested arrays show up everywhere: a tree of comments, grouped API results, or config merged from several sources. You need to collapse that nesting into a single-level array, but only down to a given depth so callers stay in control.
flatten(arr, depth) must:
- Recursively flatten nested arrays up to
depthlevels (default: flatten completely). - Preserve element order.
- Leave non-array elements untouched.
- Return a new array (don't mutate the input).
Input
flatten([1, [2, [3, [4]]]]); // depth defaults to Infinity
flatten([1, [2, [3]]], 1); // only one level
Expected output
[1, 2, 3, 4][1, 2, [3]]
Implement from scratch (no Array.prototype.flat):
function flatten(arr, depth = Infinity) {
// Your code here
}