JavaScript Array flat() Method

Beginner
⏱️ 8 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Flatten

What You’ll Learn

The flat() method flattens nested arrays into a new, simpler array. Default depth is 1; pass a number or Infinity for deeper flattening. This tutorial covers syntax, five examples, depth behavior, and how flat() differs from flatMap() and spread.

01

Syntax

flat(depth?)

02

Default

Depth 1

03

New array

No mutation

04

Infinity

Full flatten

05

Arrays only

Not objects

06

ES2019

Modern JS

Introduction

Nested arrays appear everywhere—API payloads, grid coordinates, results from map() that return arrays. The flat() method collapses those layers into a single list without manual loops.

It returns a new array and leaves the original untouched. Control how aggressive the flattening is with the optional depth argument.

Understanding the flat() Method

array.flat(depth) walks the structure and merges nested array elements into the output. Non-array values (numbers, strings, objects) are copied through unchanged.

Think of depth as how many nesting levels to unpack. flat(1) is the default; flat(2) unwraps two levels; flat(Infinity) keeps going until nothing is nested.

💡
Beginner Tip

flat() only flattens arrays. It does not drill into objects. [1, { a: [2] }].flat(Infinity) still leaves the object intact.

📝 Syntax

General form of Array.prototype.flat:

JavaScript
array.flat(depth)

Parameters

  • depth — optional; how many levels to flatten (default 1). Use Infinity for all levels.

Return value

  • A new flattened array.
  • Original array unchanged.
  • Empty slots in sparse arrays become undefined in the result.

Common patterns

  • nested.flat() — one level (default).
  • nested.flat(2) — two levels.
  • nested.flat(Infinity) — fully flat.
  • arr.map(fn).flat() — classic pre–flatMap pattern.

⚡ Quick Reference

GoalCode
Flatten one levelarr.flat() or arr.flat(1)
Flatten two levelsarr.flat(2)
Flatten completelyarr.flat(Infinity)
Mutates original?No
Flattens objects?No

📋 flat() vs flatMap() vs concat / spread vs manual loop

Pick the tool that matches whether you need flatten-only, map+flatten, or one-level merge.

flat
flatten only

Depth control

flatMap
map + flat(1)

Transform & flatten

concat / spread
one level

Merge arrays

manual loop
recursive

Pre-ES2019

Examples Gallery

Open DevTools Console (F12) or use Try-it labs. Example N maps to ?tryit=N.

📚 Getting Started

Default one-level flattening.

Example 1 — Flatten One Level (Default)

Calling flat() with no argument removes a single layer of nesting.

JavaScript
const nested = [1, [2, [3, 4, [5]]]];

const flattened = nested.flat();

console.log(flattened);
// [1, 2, [3, 4, [5]]]
Try It Yourself

How It Works

The inner array [2, [3, 4, [5]]] is merged one level. Deeper brackets around 3, 4, 5 remain.

Example 2 — Flatten Two Levels with flat(2)

Pass an explicit depth when you know how many layers to unwrap.

JavaScript
const nested = [1, [2, [3, 4, [5]]]];

const flattened = nested.flat(2);

console.log(flattened);
// [1, 2, 3, 4, [5]]
Try It Yourself

How It Works

Two flatten passes unpack [3, 4, [5]] to individual numbers plus one remaining nested [5].

📈 Practical Patterns

Full flatten, map pipelines, and mixed types.

Example 3 — Fully Flatten with flat(Infinity)

When nesting depth varies, Infinity flattens until no arrays remain.

JavaScript
const irregular = [1, [2, [3, [4, [5]]]]];

const simplified = irregular.flat(Infinity);

console.log(simplified);
// [1, 2, 3, 4, 5]
Try It Yourself

How It Works

Each nested array is recursively flattened until every element is a primitive (or non-array value).

Example 4 — Classic map().flat() Pipeline

Before flatMap(), developers flattened map results manually.

JavaScript
const sentences = ["hello world", "flat arrays"];

const words = sentences
  .map((s) => s.split(" "))
  .flat();

console.log(words);
// ["hello", "world", "flat", "arrays"]
Try It Yourself

How It Works

map produces an array of word arrays; flat() merges them one level. Modern code often uses flatMap instead.

Example 5 — Arrays Flatten; Objects Do Not

flat() ignores object properties—only array nesting is removed.

JavaScript
const mixed = [1, { tags: ["a", "b"] }, [2, 3]];

const result = mixed.flat(Infinity);

console.log(result);
// [1, { tags: ["a", "b"] }, 2, 3]
Try It Yourself

How It Works

The sub-array [2, 3] merges into the top level. The object stays as one element; arrays inside object fields are not flattened.

🚀 Common Use Cases

  • API normalization — collapse nested list responses.
  • Grid / matrix data — turn 2D arrays into 1D for processing.
  • Tokenizing text — after map(split), flatten words.
  • Tree leaves — collect leaf nodes stored as nested arrays.
  • Test fixtures — simplify deeply nested sample data.
  • Pipeline cleanup — one-level flatten after operations that return arrays.

🧠 How flat() Runs

1

Read depth

Default 1 if omitted; coerce numeric depth.

Config
2

Walk elements

For each slot, if it is an array and depth > 0, recurse.

Traverse
3

Merge into output

Append flattened children; copy non-arrays as-is.

Build
4

Return new array

Original nesting unchanged in the source.

📝 Notes

  • Default depth is 1, not full flatten.
  • flat(Infinity) is the idiomatic full-flatten shortcut.
  • Non-integer depth is truncated toward zero (invalid values behave like 0).
  • Only arrays flatten—not array-like objects unless they are true arrays.
  • Sparse arrays: holes may become undefined entries in the result.
  • ES2019—use polyfill or recursive helper for IE11.

Browser & Runtime Support

Array.prototype.flat() was added in ES2019. It is available in all evergreen browsers and modern Node.js versions.

Baseline · ES2019

Array.prototype.flat()

Supported in Chrome 69+, Firefox 62+, Safari 12+, Edge 79+, and Node 11+. Not available in Internet Explorer.

96% Modern browser support
Google Chrome Supported · Desktop & Mobile
Full support
Mozilla Firefox Supported · Desktop & Mobile
Full support
Apple Safari Supported · macOS & iOS
Full support
Microsoft Edge Supported · Chromium
Full support
Internet Explorer No native support · Use a polyfill
Polyfill
Opera Supported · Modern versions
Full support
Samsung Internet Supported · Android
Full support
Bun Supported · JavaScript runtime
Supported
Deno Supported · JavaScript runtime
Supported
Node.js Supported · Server runtime
Supported
Android WebView Supported · Modern WebView
Full support
Array.flat() Excellent

Bottom line: Safe for modern web apps. For IE11, use a polyfill or a recursive flatten helper.

Conclusion

The flat() method makes nested array data easier to work with. Choose depth deliberately: default for one level, Infinity when you need a fully flat list.

When you also need to transform elements, look at flatMap() next—it combines map and one-level flat in one step.

💡 Best Practices

✅ Do

  • Pick depth intentionally—default is only one level
  • Use flat(Infinity) for unknown nesting depth
  • Prefer flatMap when mapping and flattening together
  • Remember objects are not flattened
  • Feature-detect for very old browsers

❌ Don’t

  • Assume flat() with no args fully flattens
  • Expect nested object properties to unwrap
  • Mutate expecting the source to flatten in place
  • Use huge depth when Infinity is clearer
  • Rely on it in IE11 without a fallback

Key Takeaways

Knowledge Unlocked

Five things to remember about Array.flat()

Your foundation for flattening nested arrays in JavaScript.

5
Core concepts
📐 02

Default 1

One level.

Depth
03

Infinity

Full flatten.

All levels
🗃 04

New array

Immutable.

Safe
📦 05

Arrays only

Not objects.

Limit

❓ Frequently Asked Questions

flat() creates a new array by flattening nested sub-arrays. By default it flattens one level. You can pass a depth number or Infinity to flatten deeper.
No. flat() always returns a new array. The nested source array is not modified.
The default depth is 1, meaning one level of nesting is removed. Deeper nested arrays stay nested unless you pass a higher depth.
Infinity tells flat() to keep flattening until no nested arrays remain. Useful for irregular nesting depths.
No. flat() only flattens array elements. Objects, strings, and numbers are copied into the result as-is.
flat() is an ES2019 feature. It works in all modern browsers and Node.js 11+. Internet Explorer does not support it.
Did you know?

flatMap(fn) is defined as map(fn).flat(1) with a subtle difference: flatMap skips empty slots in sparse arrays, while map().flat() may include holes differently. For most dense arrays they behave the same.

Continue to flatMap()

Learn how to map each element to an array and flatten one level in a single method call.

flatMap() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful