How to flatten a nested array
Short answer
flat() pulls the elements of nested arrays one level up:
console.log([[1, 2], [3, 4], [5]].flat());Output:
[
1,
2,
3,
4,
5
]Any depth
The argument sets the depth. Infinity flattens everything:
const nested = [1, [2, [3, [4]]]];
console.log(nested.flat().length);
console.log(nested.flat(Infinity).join(', '));Output:
3
1, 2, 3, 4map and flat at once
flatMap() transforms each element into an array and joins the results:
const orders = [
{ items: ['tea', 'cake'] },
{ items: ['coffee'] },
];
console.log(orders.flatMap((order) => order.items).join(', '));Output:
tea, cake, coffeeCommon mistake
flat() without an argument goes only one level deep:
console.log(JSON.stringify([1, [2, [3]]].flat()));Output:
[1,2,[3]]Functions used in this recipe
- Array.prototype.flat — Flattens nested arrays into one.
- Array.prototype.flatMap — Maps each element with a function and flattens the result one level.