Array Flatten in JavaScript π
What are Nested Arrays?
A nested array is simply an array that contains other arrays inside it.
Example:
const arr = [1, [2, 3], [4, [5, 6]]];
Here:
[2, 3]is an array insidearr[5, 6]is nested even deeper
π Think of it like folders inside folders.
π€ Why Flattening Arrays is Useful?
Flattening converts a nested array into a single-level array.
Example:
[1, [2, 3], [4, [5, 6]]]
β [1, 2, 3, 4, 5, 6]
π‘ Use Cases:
API responses with nested data
Data processing pipelines
Preparing arrays for loops, maps, filters
Frontend rendering (React lists, etc.)
π§ Concept of Flattening Arrays
Flattening means:
Traverse the array β If element is an array β go inside β extract values β repeat until flat
Mental Model:
Treat nested arrays like a tree
Flattening = converting tree β list
π οΈ Different Approaches to Flatten Arrays
1οΈβ£ Using .flat() (Modern & Easiest)
const arr = [1, [2, 3], [4, [5, 6]]];
console.log(arr.flat()); // [1, 2, 3, 4, [5, 6]]
console.log(arr.flat(2)); // [1, 2, 3, 4, 5, 6]
console.log(arr.flat(Infinity)); // Fully flattened
Key Points:
Default depth = 1
Use
Infinityfor full flatten
2οΈβ£ Using Recursion (Most Important 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;
}
console.log(flattenArray([1, [2, [3, 4]], 5]));
π Why this matters:
Tests recursion understanding
Common DSA question
3οΈβ£ Using reduce()
const flatten = (arr) =>
arr.reduce((acc, item) =>
acc.concat(Array.isArray(item) ? flatten(item) : item),
[]);
console.log(flatten([1, [2, [3, 4]], 5]));
π Functional approach (clean but slightly harder to read)
4οΈβ£ Using Stack (Iterative Approach)
function flatten(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();
}
π‘ Why use this?
Avoid recursion (no call stack limits)
Good for large inputs
π§ͺ Step-by-Step Flattening Example
Letβs flatten:
[1, [2, [3]], 4]
Steps:
Take
1β push β[1]See
[2, [3]]β go insideTake
2β push β[1, 2]See
[3]β go insideTake
3β push β[1, 2, 3]Take
4β push β[1, 2, 3, 4]
π― Common Interview Scenarios
π₯ 1. Flatten to specific depth
flatten(arr, depth)
π₯ 2. Flatten without using .flat()
π Expect recursion or stack solution
π₯ 3. Handle edge cases
Empty arrays
Mixed data types
Deep nesting
π₯ 4. Performance questions
Recursion vs Iteration
Stack overflow risks
βοΈ Approach Comparison
| Method | Easy | Interview Value | Performance |
|---|---|---|---|
.flat() |
β | β Low | β Fast |
| Recursion | β οΈ | β High | β οΈ Medium |
| Reduce | β οΈ | β Medium | β οΈ Medium |
| Stack | β οΈ | β High | β Best |
π§© Final Thoughts
Flattening arrays is not just a utilityβitβs a core problem-solving pattern.
π It teaches:
Recursion
Tree traversal
Iterative thinking
If you master this, youβre building strong DSA fundamentals for:
Interviews
Real-world data handling
Scalable frontend/backend logic
π Practice Challenge
Try implementing:
flatten([1, [2, [3, [4]]]], 2)
Expected output:
[1, 2, 3, [4]]