You're given an array that may contain nested arrays, nested any number of levels deep. Implement flatten(arr) so it returns a new array with all nesting removed — every value pulled up to a single, flat level. The native version is Array.prototype.flat(Infinity); your job is to write the recursion yourself.
// Returns a new array with every nested array fully unwrapped.
// Does NOT mutate the input.
function flatten(arr: any[]): any[];
flatten([1, 2, 3]); // [1, 2, 3]
flatten([1, [2, 3]]); // [1, 2, 3]
flatten([1, [2, [3, [4]]]]); // [1, 2, 3, 4]
flatten([[[[[5]]]]]); // [5]
flatten([]); // []
flatten([1, [], [2, [3, []]]]); // [1, 2, 3]
flatten([1, 'a', [true, [null]]]); // [1, 'a', true, null]
Array.prototype.flat(Infinity) — there is no depth argument here, you go all the way down.[1, , 3]) are dropped, the same way the native flat drops them. Explicit undefined ([1, undefined, 3]) is kept.Array.isArray to decide. Objects, strings, typed arrays, and array-likes ({ 0: 'a', length: 1 }) stay as-is.arr.flat(). The whole point is to write the recursion. flat, flatMap, and JSON.parse(JSON.stringify(...)) are off-limits.