Source https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flat https://bigfrontend.dev/problem/implement-Array-prototype.flat

function flat(arr, depth = 1) {
// Recursively flatten for each depth
if (depth > 0) {
return arr.reduce((acc, val) => {
if (Array.isArray(val)) {
return [...acc, ...flat(val, depth - 1)];
} else {
return [...acc, val];
}
}, []);
// Base case if no more depth to flatten, return the new array
} else {
return arr.slice();
}
}