Array.prototype.flat returns a new array with nested arrays pulled up into the parent, down to a depth you choose. It's how you turn [1, [2, 3]] into [1, 2, 3], or collapse an arbitrarily deep tree in one call.
Implement arrayFlat(arr, depth). Flatten nested arrays up to depth levels deep. depth defaults to 1; pass Infinity to flatten completely. Like the real method, it drops holes and returns a new array without mutating the input.
function arrayFlat(arr, depth = 1) {
// returns a new array with sub-arrays flattened up to `depth` levels.
}
arrayFlat([1, [2, 3], 4]); // [1, 2, 3, 4] — one level by default
arrayFlat([1, [2, [3]]]); // [1, 2, [3]] — deeper nesting stays
arrayFlat([1, [2, [3, [4]]]], 2); // [1, 2, 3, [4]]
arrayFlat([1, [2, [3, [4]]]], Infinity); // [1, 2, 3, 4]
Infinity — flattens every level, no matter how deep.depth of 0 — no flattening; returns a shallow copy of the input.[1, , 3] flattens to [1, 3].