Flattening Arrays

You order a few things online, and a big delivery box 📦 arrives. You open it and find smaller boxes inside. One of those small boxes has an even smaller box inside it!

To actually use your things, you open every box and put all the items side by side on one table.

In JavaScript, arrays can also have arrays inside them. Taking out all those items and putting them into one simple list is called flattening.

[1, [2, 3], [4, [5, 6]]]   →   [1, 2, 3, 4, 5, 6]

What Is a Nested Array?

A nested array is an array that contains other arrays inside it.

JavaScript sees only 3 items here: the number 1, the array [2, 3], and the array [4, 5].

Levels of nesting (depth)

Each "box inside a box" adds one level, also called depth.

[1, 2, 3]              // depth 0: already flat
[1, [2, 3]]            // depth 1: one box inside
[1, [2, [3, 4]]]       // depth 2: a box inside a box
[1, [2, [3, [4]]]]     // depth 3: three boxes deep

Why Do We Need to Flatten?

Nested arrays appear a lot in real apps. For example:

  • Class sections: each section has its own list of students
  • Orders: each order has its own list of items
  • Tags: each blog post has its own list of tags

But many tasks become much easier with one flat list:

After flattening, you can count, search, sort, and loop easily.


Method 1: flat()

flat() is the easiest way to flatten an array.

Syntax

array.flat(depth)
  • depth → how many levels of boxes to open. The default is 1.
  • It returns a new array. The original array is not changed. ✅

Your first flat()

Understanding depth

By default, flat() opens only one level of boxes.

CodeWhat it does
flat() or flat(1)Opens 1 level
flat(2)Opens 2 levels
flat(Infinity)Opens every level, no matter how deep

Tip: Not sure how deep the nesting goes? Use flat(Infinity) to flatten everything completely.

Real example: all students from all sections 🏫

Real example: a train with coaches 🚆

Bonus: flat() removes empty slots

The empty spaces (holes) are cleaned up automatically.


Method 2: flatMap()

Sometimes you want to change each item and flatten the result at the same time. That is exactly what flatMap() does.

flatMap() = map() + flat(1) in one step.

Syntax

array.flatMap((item, index) => newValueOrArray);

The problem with only map()

Let us split some sentences into words:

map() gave us an array of arrays. We wanted one list of words.

✅ The fix: flatMap()

Real example: all items from all orders 🛍️

Real example: all tags from blog posts 🏷️

Trick: filtering and mapping together

With flatMap(), you can remove an item by returning [] (an empty array), or keep it by returning [value].

  • For odd numbers → return [], so nothing is added
  • For even numbers → return [n * 2], so the doubled value is added

Trick: turning one item into many

⚠️ flatMap() flattens only ONE level

If you need to go deeper, use map() followed by flat(depth).


Method 3: Flattening Without flat()

You may see these older methods in existing code, or in interview questions. They also help you understand how flattening works.

Using spread ... with concat() (one level)

Using reduce() (one level)

Using a loop (one level)

Using recursion (all levels) ⭐ Interview favourite

Recursion means a function that calls itself. It is like opening a box, and if you find another box inside, you use the same steps to open that one too.

How it works:

  1. Look at each item.
  2. Is it an array? → Flatten it using the same function, and add its items.
  3. Is it a normal value? → Add it directly.

Today, flat(Infinity) does the same work in one line. 😊


Flattening 2D Arrays (Grids)

A 2D array is an array of rows, like a cinema hall or a chess board. Flattening turns it into one long list.

Real example: total marks from a 2D array 📊


flat vs flatMap: Quick Comparison

Pointflat(depth)flatMap(fn)
What it doesOnly flattensChanges each item and flattens
DepthAny (default 1, or Infinity)Only 1 level
Takes a function?❌ No✅ Yes
Changes the original?❌ No❌ No
Best forAlready nested dataCreating lists from each item

Common Mistakes to Avoid

MistakeProblemFix
Expecting flat() to open all levelsOnly 1 level is openedUse flat(2) or flat(Infinity)
Expecting flatMap() to go deeperOnly 1 level is flattenedUse map() then flat(depth)
Using .length on a nested arrayCounts groups, not itemsFlatten first: arr.flat().length
Using includes() on a nested arrayDoesn't look inside inner arraysFlatten first, then search
Thinking flat() changes the originalIt returns a new arrayStore the result in a variable

Quick Summary Table

TaskCode
Flatten 1 levelarr.flat()
Flatten 2 levelsarr.flat(2)
Flatten everythingarr.flat(Infinity)
Map and flattenarr.flatMap((x) => [...])
Remove items in flatMapreturn []
Old way (1 level)[].concat(...arr)
Count all inner itemsarr.flat(Infinity).length

Key Takeaways

  • A nested array has arrays inside it. Flattening turns it into one simple list.
  • flat() opens 1 level by default. Use flat(2) for more levels, or flat(Infinity) for all levels.
  • flatMap() does map() and flat(1) in one step. It's great for splitting sentences or collecting items from objects.
  • Both flat() and flatMap() return a new array, so the original stays safe.
  • Flattening makes it easy to count, search, sort, and total items that were spread across many inner arrays.