Flatten a nested array
Write flatten(arr, depth = Infinity) that returns a new array with nested arrays flattened up to depth levels deep, without using Array.prototype.flat.
flatten([1, [2, [3, [4]]]])→[1, 2, 3, 4]flatten([1, [2, [3, [4]]]], 1)→[1, 2, [3, [4]]]flatten([[], [[]], 5])→[5]flatten([1, [2]], 0)→[1, [2]](a shallow copy)
Only arrays get flattened: objects, strings and null stay as they are. Don't mutate the input.
Define flatten in the editor. 7 tests will call it.
Hint 1Loop over the items and push each one into a result array, unless it is an array you still need to flatten.
Hint 2When an item is an array and depth is greater than 0, flatten it recursively with depth - 1 and push the items it returns.
Hint 3Array.isArray(item) tells you whether an item is an array. With depth 0 (or less) every item is copied as it is.
one clean solution
function flatten(arr, depth = Infinity) {
const result = [];
for (const item of arr) {
if (Array.isArray(item) && depth > 0) {
for (const inner of flatten(item, depth - 1)) result.push(inner);
} else {
result.push(item);
}
}
return result;
}