Array Flatten in JavaScript
If you've worked with APIs, dynamic data, or coding interview questions, you've probably encountered something like this:
const nestedArray = [
[1, 2, [3, 4]],
[5, [6, [7]]],
[[8], 9]
];
At first glance, it looks harmless.
But the moment you try to loop through it, calculate totals, filter values, or render it in the UI… things get messy fast.
What you really want is this:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
This process is called array flattening — one of the most important JavaScript concepts you'll face in real-world development and technical interviews.
And once you truly understand it, nested arrays stop feeling scary.
What Exactly Is a Nested Array?
A nested array is simply an array that contains other arrays inside it.
Think of it like folders inside folders.
const data = [
[1, 2],
[3, [4, 5]],
[[6]]
];
Visual representation:
Level 0: [
Level 1: [1, 2],
Level 1: [3, [4, 5]],
Level 1: [[6]]
]
Some arrays go one level deep.
Others go many levels deep.
And that’s where flattening becomes useful.
Why Does Array Flattening Matter?
This isn't just a random interview topic.
Flattening solves actual problems developers face every day.
1. API Responses Are Often Nested
Real-world APIs frequently return deeply structured data.
Example:
const users = [
{
name: "Alice",
hobbies: ["Reading", "Coding"]
},
{
name: "Bob",
hobbies: ["Gaming", ["Chess", "Poker"]]
}
];
Now imagine trying to search, filter, or display hobbies cleanly.
Nested structures quickly become painful.
2. Flat Arrays Are Easier to Process
Before flattening:
for (let i = 0; i < arr.length; i++) {
// nested loops
}
After flattening:
flatArray.reduce((sum, num) => sum + num, 0);
Cleaner. Faster. More readable.
3. Interviewers Love This Question
Why?
Because array flattening tests:
Recursion
Problem-solving
Iteration
Functional programming
Time complexity understanding
Master this once, and you'll unlock multiple interview concepts at the same time.
The Core Idea Behind Flattening
Flattening means:
“Take elements from nested arrays and move them into a single array.”
Example:
Input:
[
[1, 2, [3, 4]],
[5, [6, [7]]]
]
Output:
[1, 2, 3, 4, 5, 6, 7]
The challenge is deciding:
How deep should flattening go?
Should we use recursion?
Should we use loops?
What about performance?
Let’s explore the best approaches.
Approach 1 — The Built-in flat() Method (Simplest Solution)
Modern JavaScript gives us a native method for flattening arrays.
const nested = [1, [2, [3, [4]]], 5];
const flat = nested.flat(Infinity);
console.log(flat);
Output:
[1, 2, 3, 4, 5]
Understanding Infinity
flat(Infinity)
means:
“Keep flattening until there are no nested arrays left.”
You can also flatten specific levels:
arr.flat(1); // Flatten one level
arr.flat(2); // Flatten two levels
Why Developers Love It
Extremely readable
Short and clean
Native performance
Great for production apps
Limitations
Not supported in older browsers like Internet Explorer
Less flexible for custom logic
Still, this should usually be your first choice.
Approach 2 — reduce() + Recursion (Interview Favorite)
This is the classic interview solution.
function flatten(arr) {
return arr.reduce((acc, val) => {
return Array.isArray(val)
? acc.concat(flatten(val))
: acc.concat(val);
}, []);
}
const result = flatten(nestedArray);
console.log(result);
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Why This Works
The function checks:
Array.isArray(val)
If the value is an array:
flatten(val)
It recursively flattens it.
Otherwise:
acc.concat(val)
It adds the value directly to the result.
Step-by-Step Mental Model
Imagine this:
flatten([1, [2, [3]]])
Step 1
1 → add directly
Step 2
[2, [3]] → recurse
Step 3
2 → add directly
Step 4
[3] → recurse again
Eventually everything becomes flat.
This is recursion in action.
Approach 3 — Stack-Based Iteration (Best for Massive Arrays)
Recursion is elegant.
But for extremely large arrays, recursion can crash with:
Maximum call stack size exceeded
That’s where iterative flattening shines.
function flattenIterative(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.push(item);
}
}
return result.reverse();
}
Why This Approach Is Powerful
Instead of relying on the JavaScript call stack, we create our own stack manually.
This avoids recursion depth issues.
Perfect for:
Huge datasets
Performance-heavy systems
Production-scale applications
Approach 4 — flatMap() (Flatten + Transform Together)
flatMap() is amazing when you need:
transformation
and flattening
at the same time.
const nested = [[1, 2], [3, 4]];
const doubled = nested.flatMap(arr =>
arr.map(num => num * 2)
);
console.log(doubled);
Output:
[2, 4, 6, 8]
Why flatMap() Is Useful
Without flatMap():
arr.map(...).flat()
With flatMap():
arr.flatMap(...)
Cleaner and more efficient.
Approach 5 — The “JSON Hack” (Fun but Dangerous)
Yes, people actually do this.
const nested = [1, [2, [3]]];
const flat = JSON.parse(
'[' + JSON.stringify(nested).replace(/\[/g, '') + ']'
);
console.log(flat);
It works…
But please don’t use this in real applications.
Why This Is Dangerous
It destroys:
functions
objects
dates
undefined values
Use it only as a fun experiment or quick prototype.
Real Interview Variations
Interviewers rarely ask the “basic” version only.
Here are common twists.
1. Flatten to a Specific Depth
function flattenDepth(arr, depth = 1) {
return depth > 0
? arr.reduce((acc, val) => acc.concat(
Array.isArray(val)
? flattenDepth(val, depth - 1)
: val
), [])
: arr.slice();
}
Example:
flattenDepth([1, [2, [3]]], 1);
Output:
[1, 2, [3]]
2. Handle Massive Arrays
If the dataset contains:
hundreds of thousands
or millions of elements
prefer:
✅ iterative stack solution
instead of recursion.
Performance Comparison
| Method | Time Complexity | Memory | Best Use Case |
|---|---|---|---|
flat(Infinity) |
O(n) | O(n) | Modern applications |
Recursive reduce() |
O(n) | O(d) | Interviews |
| Iterative stack | O(n) | O(n) | Huge arrays |
flatMap() |
O(n) | O(n) | Transform + flatten |
Where:
n= total elementsd= recursion depth
Common Edge Cases Developers Forget
Always test these:
Empty Arrays
[]
Mixed Data Types
[1, "hello", [true, null]]
Deep Nesting
[[[[[[1]]]]]]
Circular References
const arr = [];
arr.push(arr);
This can create infinite recursion if not handled carefully.
The Best Way to Think About Flattening
Whenever you see nested arrays, ask yourself:
1. How deep is the nesting?
One level? Infinite levels?
2. How large is the data?
Small arrays → recursion is fine
Massive arrays → iterative approach is safer
3. Do I need transformations too?
If yes:
flatMap()
might be perfect.
Final Thoughts
Array flattening is one of those JavaScript concepts that looks simple…
until you truly understand what’s happening under the hood.
But once you master it, you start recognizing flattening problems everywhere:
API responses
UI rendering
Data pipelines
Algorithms
Interview questions
And the best part?
Learning flattening also teaches you:
recursion
stacks
iteration
functional programming
performance optimization
—all from one problem.
So next time you see a deeply nested array…
you won’t panic.
You’ll flatten it like a pro.
