Skip to content
Tutorials Center
My learning

Topics

JavaScript Reference ยท Array

JavaScript Array flat() method

Reference for JavaScript Array flat(): flatten nested arrays to a chosen depth into a new array, with Infinity, holes, and examples of common pitfalls.

The flat() method creates a new array in which the elements of nested arrays are pulled up into the outer array, down to a depth you choose. The default depth is 1, so only one level of nesting is removed.

The original array is not changed. Pass Infinity to flatten however deep the nesting goes.

JavaScript
[1, [2, [3]]].flat(); // [1, 2, [3]]

Try it

JS Choosing the depth

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS Holes and real-world use

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
flat()
flat(depth)
Name Description
depth Optional. How many levels of nested arrays to flatten. Default 1. 0 copies without flattening; Infinity flattens fully.

Return value: a new array containing the flattened elements.

Exceptions: none for ordinary arrays.

Usage notes

  • One level by default. [1, [2, [3]]].flat() leaves [3] nested. Pass a larger number or Infinity for deeper structures.
  • Only real arrays are flattened. Array-like objects, strings and objects stay as they are, since flat() checks for actual arrays.
  • Holes disappear. Empty slots in the array and in the nested arrays are dropped, as the first line of the second example shows. This makes flat() a handy way to remove holes.
  • Shallow copy. Objects inside the arrays are shared with the original, so changing one changes both.
  • map() then flat() equals flatMap(). If you map each element to an array and flatten one level, flatMap() does it in one pass.
  • Concatenating lists: [].concat(...arrays) or arrays.flat() both join an array of arrays; flat() is clearer.

Browser support

flat() is supported in current browsers. It is newer than the classic array methods, so check a compatibility table if you must support very old environments.