Array Flatten in JavaScript

Flattening arrays is one of those concepts that looks simple—but shows up in interviews, real-world data handling, and problem-solving all the time.
What are Nested Arrays?
A nested array is simply an array inside another array.
const arr = [1, [2, 3], [4, [5, 6]]]
Visual Representation:
[
1,
[2, 3],
[4, [5, 6]]
]
Think of it like layers:
Level 1 → Main array
Level 2 → Arrays inside it
Level 3 → Arrays inside those arrays
Why flattening arrays is useful?
In real-world applications, data is often nested:
API responses (comments, categories, trees)
File structures
UI components (menus, nested lists)
Problem:
Nested data is harder to:
Iterate
Search
Transform
Solution:
Flatten it into a single-level array
[1, 2, 3, 4, 5, 6]
Concept of Flattening Arrays
Flattening means:
Taking all elements from nested levels and bringing them into one single array.
Transformation Idea:
Before: [1, [2, [3, 4]], 5]
Step 1 → Open first layer
Step 2 → Keep digging deeper
Step 3 → Collect values
After: [1, 2, 3, 4, 5]
Different Approaches to Flatten Array
- Built-In Method:
flat()
The easiest and most modern way
Key Point:
Infinity→ Flattens all levels
const arr = [1, [2, [3, 4]], 5];
console.log(arr.flat(Infinity));
// Output: [1, 2, 3, 4, 5]
- Using Recursion: (Most common for interviews):
function flattenArray(arr) {
let result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result = result.concat(flattenArray(item));
} else {
result.push(item);
}
}
return result;
}
const arr = [1, [2, [3, 4]], 5];
console.log(flattenArray(arr));
- Using
reduce():
A cleaner functional approach.
const flattenArray = (arr) => {
return arr.reduce((acc, curr) => {
return acc.concat(
Array.isArray(curr) ? flattenArray(curr) : curr
);
}, []);
};
- Using Stack (Iterative Approach):
Useful when avoiding recursion.
function flattenArray(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.push(next);
}
}
return result.reverse();
}
Common Interview Questions
You’ll often see variations like:
Flatten Only One Level
arr.flat(1);Flatten to Specific Depth
arr.flat(2);
Flatten Without Using
flat(). Use recursion or reduceHandle Deeply Nested Arrays
[1, [2, [3, [4, [5]]]]]
- Flatten + Transform
// Double values while flattening
Conclusion
Flattening arrays isn’t just a coding trick—it’s about:
Breaking down problems
Handling nested structures
Thinking recursively
Master this, and you’ll handle trees, JSON data, and complex structures much more easily.






