Array.prototype.flat()

Returns a new array with nested sub-arrays merged into it, up to a chosen depth.

Signature
flat()
flat(depth)
  • Added in JavaScript ECMAScript 2019

Parameters

ParameterTypeDescription
$depthoptionalnumber= 1How many levels of nesting to flatten. Pass Infinity to flatten every level.

Return value

ArrayA new array with the sub-array elements concatenated into it recursively up to the specified depth.

Errors

Throws a TypeError if called on null or undefined; a RangeError is possible if the result would exceed the maximum array length.

flat() copies the array and splices the contents of any element that is itself an array into the result. It stops after depth levels, which defaults to 1 — the single most common source of surprise, because one call does not fully flatten a tree.

When to reach for it

Use it whenever a map() produced arrays instead of values: grouped query results, per-file lists of matches, children of children. If the array-producing step is right next to the flatten step, flatMap() does both in one pass and avoids the intermediate array.

What trips people up

  • flat() is shallow in the copying sense — the elements that survive are the same object references, not clones.
  • It drops empty slots in sparse arrays. [1, , 3].flat() is [1, 3], length 2, while [1, , 3].map(x => x) keeps the hole.
  • Only real arrays are unwrapped. Array-like objects, strings and Sets pass through untouched — ["ab"].flat() is still ["ab"].
  • Non-integer or negative depths are truncated toward zero, and flat(0) is just a shallow copy.

The original array is never modified, so flat() is safe on frozen arrays and on state you must not mutate.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Flatten per-page results from a paginated fetch into one list of records.
  • Collapse a nested category tree into a single array of leaf nodes with flat(Infinity).
  • Clean up an array built from several map() calls that each returned arrays.
  • Strip empty slots out of a sparse array in the same step as flattening.

Frequently asked questions

How do I flatten an array completely in JavaScript?

Call flat(Infinity) — it keeps unwrapping until no element is an array. The default depth of 1 only removes one level, so [1, [2, [3]]].flat() still leaves [3] nested inside.

Does flat() change the original array?

No, flat() is a copying method that returns a new array and leaves the receiver untouched. That also means it works on frozen arrays and on values you must not mutate, such as React state.

Why did flat() delete elements from my array?

It removes empty slots from sparse arrays, so [1, , 3].flat() has length 2. Holes created by delete, by Array(n), or by assigning past the end all disappear; use Array.from() or fill() first if you need them preserved as undefined.

More examples

Joining grouped rows

One level of flattening merges every page into a single list. Empty inner arrays simply contribute nothing, so the result has 5 items rather than a hole where the empty page was.

Example · javascript
const pages = [
  ["a", "b"],
  ["c"],
  [],
  ["d", "e"],
];

const all = pages.flat();
console.log(all);
console.log(all.length);

flat(1) is not deep

After one level the result still contains an array at index 1, so isArray() reports true. Only flat(Infinity) reduces the structure to plain numbers.

Example · javascript
const tree = [[1, [2]], [3]];

const shallow = tree.flat();
console.log(shallow);
console.log(shallow.length);
console.log(Array.isArray(shallow[1]));

console.log(tree.flat(Infinity));

Strings and Sets are not unwrapped

flat() only expands values for which Array.isArray() is true. A string stays one element and a Set stays one element; you have to convert them to arrays yourself.

Example · javascript
console.log(["ab", ["cd"]].flat());
console.log([new Set([1, 2]), 3].flat());

// Convert first if you want them flattened
console.log([new Set([1, 2]), 3].flat().flatMap((v) => (v instanceof Set ? [...v] : v)));

Discussion

  • Be the first to comment on this lesson.