Flatten Nested Arrays
Capstone time. An array can contain numbers or more arrays, nested any
number of levels deep. You already learned the key check β Array.isArray β
so now you just wire it into a recursion.
Walk each item: if it's an array, flatten it and merge the result; if it's a number, keep it. The base case here is subtle β it's reaching a plain number (an item that isn't an array), so there's nothing deeper to recurse into.
function flatten(arr) {
let result = [];
for (const item of arr) {
if (Array.isArray(item)) result = result.concat(flatten(item)); // recurse + merge
else result.push(item); // keep the number
}
return result;
}
flatten([1, [2, [3, 4]], 5]); // [1, 2, 3, 4, 5]
result.concat(flatten(item)) merges the flattened sub-array onto what we have
so far; result.push(item) adds a single number. An empty input array just
returns the empty result.
Your task
Write flatten(arr) that returns a single flat array of all the numbers, in
order, no matter how deeply nested. Don't use the built-in Array.prototype.flat.
π§± Code blocks
Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.
Run your code to check these.