Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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, 4

map 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, coffee

Common 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

Thanks for reading!

Donate to the site — we work hard for you.