Array Flatten in JavaScript

What is a Nested Array
A nested array is just an array that contains other arrays.
const arr = [1, [2, [3, 4], 5]];
The problem is simple. You don’t want this structure. You want everything in a single level.
Why Flattening Matters
Real data is rarely clean.
API responses often return nested structures
Tree-like data (comments, categories) comes nested
You often need a flat list to process or display
If you can’t flatten properly, you’ll struggle with real-world data.
Core Idea
This is the entire logic:
If the item is not an array, collect it
If the item is an array, go inside it
You keep going deeper until there are no more arrays.
Execution Flow (Think Like This)
Start from left
Push values when they are not arrays
Dive deeper when you hit an array
Come back (backtrack) and continue
Step by Step Dry Run
Input:
[1, [2, [3, 4], 5]]
Execution:
See
1→ not array → push →[1]See
[2, [3,4], 5]→ array → go insideNow inside:
See
2→ push →[1, 2]See
[3,4]→ array → go insideNow inside:
See
3→ push →[1,2,3]See
4→ push →[1,2,3,4]
Done → return back
See
5→ push →[1,2,3,4,5]
Done
Final result:
[1, 2, 3, 4, 5]
If you don’t understand this flow, the code will look like magic.
Flattening of array
1. Built-in Method
arr.flat(Infinity);
2. Recursive
function flatten(arr) {
let result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result = result.concat(flatten(item));
} else {
result.push(item);
}
}
return result;
}
3. Using reduce
function flatten(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
return acc.concat(flatten(item));
}
return acc.concat(item);
}, []);
}
4. Iterative
function flatten(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();
}
Interview Angle
What they are testing:
Can you identify recursive structure
Can you break problem into smaller identical subproblems
Do you handle nested depth correctly
Common mistakes:
Forgetting to handle deeply nested arrays
Mutating the result incorrectly
Not understanding when recursion stops




