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 is1.- 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.
| Code | What 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:
- Look at each item.
- Is it an array? → Flatten it using the same function, and add its items.
- 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
| Point | flat(depth) | flatMap(fn) |
|---|---|---|
| What it does | Only flattens | Changes each item and flattens |
| Depth | Any (default 1, or Infinity) | Only 1 level |
| Takes a function? | ❌ No | ✅ Yes |
| Changes the original? | ❌ No | ❌ No |
| Best for | Already nested data | Creating lists from each item |
Common Mistakes to Avoid
| Mistake | Problem | Fix |
|---|---|---|
Expecting flat() to open all levels | Only 1 level is opened | Use flat(2) or flat(Infinity) |
Expecting flatMap() to go deeper | Only 1 level is flattened | Use map() then flat(depth) |
Using .length on a nested array | Counts groups, not items | Flatten first: arr.flat().length |
Using includes() on a nested array | Doesn't look inside inner arrays | Flatten first, then search |
Thinking flat() changes the original | It returns a new array | Store the result in a variable |
Quick Summary Table
| Task | Code |
|---|---|
| Flatten 1 level | arr.flat() |
| Flatten 2 levels | arr.flat(2) |
| Flatten everything | arr.flat(Infinity) |
| Map and flatten | arr.flatMap((x) => [...]) |
| Remove items in flatMap | return [] |
| Old way (1 level) | [].concat(...arr) |
| Count all inner items | arr.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. Useflat(2)for more levels, orflat(Infinity)for all levels.flatMap()doesmap()andflat(1)in one step. It's great for splitting sentences or collecting items from objects.- Both
flat()andflatMap()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.