Array Flatten in JavaScript

[1, [2, [3, 4]]]
You need one flat line. [1, 2, 3, 4]
This is array flattening.
Let me show you how.
What Are Nested Arrays?
Array ke andar array.
const nested = [1, [2, 3], 4];
// ^ ^
// number array inside
You can go deeper:
const deep = [1, [2, [3, [4]]]];
// Russian dolls. Array inside array inside array.
Why Flatten Arrays? Real Use Cases
Real data is messy.
| Scenario | Why flatten? |
|---|---|
| API gives nested comments | Show all comments in one list |
| Matrix (2D array) | Loop without double loops |
| Merge multiple arrays | One clean array |
| Tree categories → all subcategories | Get every leaf node |
Example: Get all tags from blog posts.
const posts = [
{ title: "JS", tags: ["js", "frontend"] },
{ title: "Python", tags: ["py", "backend"] }
];
const allTags = posts.flatMap(post => post.tags);
// ["js", "frontend", "py", "backend"]
Flatten = turn complex into simple.
The Concept of Flattening
Open every box. Take everything out. Put into one box.
Step by step:
Start: [1, [2, 3], 4]
Step 1: 1 → keep
Step 2: [2, 3] → open → 2, then 3
Step 3: 4 → keep
Result: [1, 2, 3, 4]
If deeper, repeat until no arrays left.
Different Approaches to Flatten Arrays
Approach 1: Modern Way – flat()
const arr = [1, [2, [3, [4]]]];
arr.flat(); // [1, 2, [3, [4]]] (one level only)
arr.flat(2); // [1, 2, 3, [4]]
arr.flat(Infinity); // [1, 2, 3, 4] ← fully flat
Use flat(Infinity) when you don't know the depth.
Approach 2: Manual Way – reduce() + Recursion
Want to understand how it works? Build it yourself.
function flatten(arr) {
return arr.reduce((acc, val) => {
if (Array.isArray(val)) {
return acc.concat(flatten(val));
} else {
return acc.concat(val);
}
}, []);
}
flatten([1, [2, [3, 4]]]); // [1, 2, 3, 4]
Approach 3: Simple Way – concat() + Spread (One Level Only)
const oneLevel = [1, [2, 3], 4];
[].concat(...oneLevel); // [1, 2, 3, 4]
Works only for shallow nesting.
Comparison – Which Method to Use?
| Method | Depth | Best for |
|---|---|---|
flat(Infinity) |
Any | Modern code, any depth |
reduce + recursion |
Any | Learning / custom logic |
concat + spread |
One level | Quick shallow flatten |
Recommendation: Use flat(Infinity) unless you support very old browsers.
Common Mistakes
Mistake 1: Forgetting flat() only goes one level by default
const deep = [1, [2, [3, [4]]]];
deep.flat(); // [1, 2, [3, [4]]] ← not fully flat!
deep.flat(Infinity); // ✅
Mistake 2: Trying to flatten objects
flat() only works on arrays.
const obj = { a: [1,2], b: [3,4] };
obj.flat(); // ❌ TypeError
Fix: Use Object.values(obj).flat().
Mistake 3: Mutating original array
flat() returns a new array. Original stays unchanged.
const original = [1, [2]];
const flattened = original.flat();
console.log(original); // [1, [2]] ✅ unchanged
Final Thought
Flattening is simple: open every box, take everything out, put into one line.
Use
flat(Infinity)




