References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript array.flat() method

Method JavaScript All modern browsers Updated
Quick answer

The flat() method flattens nested arrays into a single array. [1, [2, 3], [4]].flat() gives [1, 2, 3, 4]. By default it flattens one level deep; pass a number for more, or Infinity to flatten completely. It returns a new array and leaves the original alone.

Overview

flat() smooths out nested arrays. An array containing other arrays — [1, [2, 3], [4, [5]]] — becomes flatter when you call flat() on it. By default it goes just one level deep, so that example flattens to [1, 2, 3, 4, [5]] — the doubly-nested [5] stays nested.

To go deeper, pass a depth: flat(2) flattens two levels. When you don't know how deep the nesting goes, flat(Infinity) flattens it completely, however many levels there are. It returns a new array, so the original is untouched, and it also drops empty slots from sparse arrays along the way.

A close relative is flatMap(), which maps each element and then flattens the result one level — handy when a map() callback returns arrays you want merged. If you find yourself writing arr.map(...).flat(), flatMap() does it in one step.

Syntax

array.flat()          // one level (default)
array.flat(depth)     // n levels
array.flat(Infinity)  // fully flatten

[1, [2, [3]]].flat()        // [1, 2, [3]]
[1, [2, [3]]].flat(Infinity) // [1, 2, 3]

Parameters

The array.flat() method accepts the following parameters.

Parameter Description
depth Optional. How many levels deep to flatten. Defaults to 1. Use Infinity to flatten all levels.

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const nested = [1, [2, 3], [4, [5, 6]]];

  document.getElementById('out').textContent =
    'flat():    ' + JSON.stringify(nested.flat()) + '\n' +
    'flat(Inf): ' + JSON.stringify(nested.flat(Infinity));
</script>

Best practices

  • Pass Infinity when the nesting depth is unknown and you want it fully flat.
  • Use flatMap() instead of map().flat() when a map callback returns arrays.
  • Remember the default depth is just 1 level.
  • It returns a new array — the original nested structure is unchanged.

Frequently asked questions

What does flat() do in JavaScript?
It flattens nested arrays into a single array, one level deep by default.
How do I fully flatten a deeply nested array?
Pass Infinity as the depth: arr.flat(Infinity).
What is the difference between flat() and flatMap()?
flat() only flattens; flatMap() maps each element with a callback and then flattens the result one level — equivalent to map().flat().
Does flat() change the original array?
No. It returns a new, flatter array and leaves the original as it was.