Array Flatten in JavaScript
What are Nested Arrays?
A nested array is simply an array inside another array.
Example:
const arr = [1, 2, [3, 4], [5, [6, 7]]];
Think of it like folders inside folders .
Why Flattening Arrays is Useful?
Flattening means converting a nested array into a single-level array.
Why this matters:
Easier to loop through data
Required for APIs / data processing
Useful in frontend rendering (React lists, etc.)
Simplifies calculations (sum, filter, map)
Example:
[1, 2, [3, 4]] → [1, 2, 3, 4]
Concept of Flattening (Step-by-Step Thinking)
Take this:
[1, [2, [3, 4]]]
Step-by-step:
Start with empty result →
[]Read
1→ push →[1]See
[2, [3, 4]]→ go insideRead
2→[1, 2]See
[3, 4]→ go insidePush
3,4→[1, 2, 3, 4]
Key idea:
If element is an array → go deeper (recursion)
If not → add to result
Different Approaches to Flatten Arrays
1. Built-in Method (flat())
const arr = [1, [2, [3, 4]]];
arr.flat(Infinity);
// [1, 2, 3, 4]
2. Using Recursion(most important)
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 Stack (Iterative Approach)
function flatten(arr) {
let stack = [...arr];
let result = [];
while (stack.length) {
let item = stack.pop();
if (Array.isArray(item)) {
stack.push(...item);
} else {
result.push(item);
}
}
return result.reverse();
}
4. Using reduce()
function flatten(arr) {
return arr.reduce((acc, curr) => {
return acc.concat(Array.isArray(curr) ? flatten(curr) : curr);
}, []);
}
Common Interview Scenarios
- Flatten to a specific depth
arr.flat(2)
Flatten without using built-in methods
Handle very deeply nested arrays
recursion vs stack discussionFlatten + remove duplicates
[1, [2, 2], [3]] → [1, 2, 3]
- Flatten + transform
[1, [2, 3]] → [2, 4, 6] (map while flattening)
Problem-Solving Thinking (What Interviewers Want)
When you see a nested array:
Ask yourself:
Is this recursive in nature? → YES
What is the base case? → Not an array
What should I do with sub-arrays? → Flatten them