Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.flat

Flattens nested arrays into one.

Available since: ES2019

Syntax

array.flat(depth)

Parameters

ParameterTypeDescription
depthnumberOptional. How many levels of nesting to unpack. 1 by default.

Return value

ArrayA new flattened array.

Examples

One level of nesting:

console.log([[1, 2], [3, 4]].flat().join(', '));

Output:

1, 2, 3, 4

Deep nesting — depth or Infinity:

const nested = [1, [2, [3, [4]]]];
 
console.log(nested.flat().length);
console.log(nested.flat(Infinity).join(', '));

Output:

3
1, 2, 3, 4

Notes

Empty slots (like in [1, , 3]) are removed. The original array is not changed.

See also

Related recipes

In the tutorial

  • Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.

Thanks for reading!

Donate to the site — we work hard for you.