How do you flatten a nested array in JavaScript?
The built-in flat method flattens a nested array. By default it removes one level of nesting, and you can give it a number to say how many levels it should remove.
const nested = [1, [2, 3], [4, [5, 6]]];
console.log(nested.flat()); // [ 1, 2, 3, 4, [ 5, 6 ] ] - one level
console.log(nested.flat(Infinity)); // [ 1, 2, 3, 4, 5, 6 ] - every level
const deeper = [1, [2, [3, [4]]]];
console.log(deeper.flat(2)); // [ 1, 2, [ 3, [ 4 ] ] ]
// The manual version, written out step by step.
const manual = [];
for (const item of nested) {
if (Array.isArray(item)) {
for (const inner of item) {
manual.push(inner);
}
} else {
manual.push(item);
}
}
console.log(manual); // [ 1, 2, 3, 4, [ 5, 6 ] ]
The manual version is worth understanding, because it shows what flat is really doing. The loop walks through the outer array, and when it finds an array inside, it moves each of the items of that inner array into the new list. The items that are not arrays are added as they are. That is exactly what flat does with its default depth of one.
Passing Infinity flattens everything, but you need to be careful with it on data that you did not create yourself. If the structure has a loop in it, meaning an array contains itself directly or through another array, then flattening it never ends and your program runs out of memory. Even without a loop, flattening a very deep structure with Infinity is slower than flattening only as deep as you actually need, because the method still has to walk the whole structure.
Two practical notes to finish. flat only flattens arrays, so an object that holds an array inside it is left alone. And flat skips the empty slots in a sparse array instead of turning them into empty values.