Flattening arrays is one of those concepts that shows up everywhere—from real-world coding tasks to technical interviews.
In JavaScript, flattening an array refers to converting a nested (multi-dimensional) array into a single-level array by extracting all sub-elements.
What nested arrays are
Nested arrays, also known as multi-dimensional arrays, are arrays that contain other arrays as elements.
They represent hierarchical data, such as a grid, tree-like structures, or complex API responses.
Example:
const nestedArray = [1, [2, 3], [4, [5, 6]]];
Visual Representation:
[ 1, [ 2, 3 ], [ 4, [ 5, 6 ] ] ]
Tree view:
[]
/ | \
1 [] []
/ \ / \
2 3 4 []
/ \
5 6
Why flattening arrays is useful
Flattening converts a nested array into a single-level array.
Data Normalization: Converts complex tree-like structures from API responses into simple lists for easier processing.
Simplified Manipulation: Operations like sorting, searching, or mapping are significantly easier on a flat array than a deeply nested one.
Compatibility: Many UI components, such as simple drop downs or search autocomplete lists, require flat data structures
Benefits:
- Easier data processing
- Simplifies loops and iterations
- Useful in APIs and data transformations
- Common in functional programming tasks
Example:
Input: [1, [2, 3], [4, [5, 6]]]
Output: [1, 2, 3, 4, 5, 6]
Visual Tree Representation
[]
/ | \
1 [] []
/ \ / \
2 3 4 []
/ \
5 6
Step-by-Step Flattening
Step 1: Start reading from left to right
Take: 1
Result: [1]
Step 2: Encounter [2, 3]
Open the box → take elements inside
Result: [1, 2, 3]
Step 3: Encounter [4, [5, 6]]
Open it:
Take: 4
Result: [1, 2, 3, 4]
Now see another nested box → [5, 6]
Step 4: Open [5, 6]
Take: 5, 6
Result: [1, 2, 3, 4, 5, 6]
Flatten Transformation Diagram
Original:
[1, [2, 3], [4, [5, 6]]]
Step 1:
[1, 2, 3, [4, [5, 6]]]
Step 2:
[1, 2, 3, 4, [5, 6]]
Step 3:
[1, 2, 3, 4, 5, 6]
Final Output
[1, 2, 3, 4, 5, 6]
Concept of flattening arrays
Flattening arrays means converting a nested (multi-level) array into a single-level array by removing all inner array layers.
Flattening arrays is more than just “removing brackets”—it’s about systematically breaking down a complex structure into a simple, usable form.
Transformation Visual:
Before: [1, [2, 3], [4, [5, 6]]]
Step 1: [1, 2, 3, [4, [5, 6]]]
Step 2: [1, 2, 3, 4, [5, 6]]
Step 3: [1, 2, 3, 4, 5, 6]
Visual Idea:
[]
/ | \
1 [] []
/ \ / \
2 3 4 []
/ \
5 6
Step-by-Step Deep Understanding
Start: [1, [2, 3], [4, [5, 6]]]
Step 1:
→ 1 is not an array → add
Result: [1]
Step 2:
→ [2, 3] is an array → go inside
→ 2 → add
→ 3 → add
Result: [1, 2, 3]
Step 3:
→ [4, [5, 6]] is an array → go inside
→ 4 → add
→ [5, 6] → go inside
→ 5 → add
→ 6 → add
Final Result: [1, 2, 3, 4, 5, 6]
Why This Concept Matters
Understanding flattening helps you:
- Solve recursive problems
- Work with tree-like data (DOM, JSON)
- Handle real-world nested API responses
- Crack coding interviews
Different approaches to flatten array
In JavaScript, you can flatten arrays using built-in methods like Array.prototype.flat(), functional approaches such as reduce() with recursion, or iterative solutions using a stack to avoid call stack limits.
Built-in Methods
flat(depth): Introduced in ES2019, this is the standard way to create a new flattened array.
Default: Flattens one level deep.
Unlimited Depth: Pass Infinity to fully flatten an array regardless of nesting.
Sparse Arrays: Automatically removes empty slots.
flatMap(): Combines mapping and flattening into one step, useful for transforming data from nested API responses.
Example 1: Default Behaviour (Depth = 1)
const arr = [1, [2, 3], [4, 5]];
arr.flat();
// [1, 2, 3, 4, 5]
Visual:
Before: After:
[ [
1, 1,
[2, 3], ----> 2,
[4, 5] 3,
] 4,
5
]
Example 2: Deeper Nesting
const arr = [1, [2, [3, 4]]];
arr.flat();
// [1, 2, [3, 4]]
- It flattened only the first level
- [3, 4] is still nested
Example 3: Using Depth
const arr = [1, [2, [3, [4]]]];
arr.flat(2);
// [1, 2, 3, [4]]
Visual:
Depth = 2
[1, [2, [3, [4]]]]
↓ ↓
[1, 2, 3, [4]]
Example 4: Flatten Completely
const arr = [1, [2, [3, [4, 5]]]];
arr.flat(Infinity);
// [1, 2, 3, 4, 5]
Recursive Approach
A recursive approach is a way of solving a problem where a function calls itself repeatedly to break the problem into smaller, simpler parts until a stopping condition is reached.
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;
}
Break the problem into smaller sub problems.
Using reduce()
Using reduce(), flattening an array means iterating through each element and accumulating results into a single array, while recursively handling nested arrays.
function flatten(arr) {
return arr.reduce((acc, item) => {
return acc.concat(
Array.isArray(item) ? flatten(item) : item
);
}, []);
}
Iterative (Stack-Based)
The iterative (stack-based) approach is a way of flattening an array by using a stack (LIFO structure) to process elements one by one, instead of using recursion.
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();
}
*Common interview scenarios *
"Flatten this without using .flat()": They want to see recursion or a while loop.
"Flatten to a specific depth": They want to see if you can add a depth counter to your recursive function.
"Handle empty slots": How does your code handle [1, , [3]]? (The built-in .flat() removes empty slots).
Nested Array Structure:
Tree / Hierarchy View (Best for understanding depth)
Array
├── 1
├── [2, 3]
│ ├── 2
│ └── 3
└── [4, [5, 6]]
├── 4
└── [5, 6]
├── 5
└── 6
Visualisation:
[ 1, [ 2, 3 ], [ 4, [ 5, 6 ] ] ]
└───┘ └───────┘
level 1 level 2
Layered Depth View
Level 0: [ 1, A, B ]
Level 1: [2, 3] [4, C ]
Level 2: [5, 6]
Flatten Transformation Visual:
Step-by-Step Expansion:
Step 1:
[1, [2, 3], [4, [5, 6]]]
Step 2 (open first level):
[1, 2, 3, 4, [5, 6]]
Step 3 (open next level):
[1, 2, 3, 4, 5, 6]
Arrow Transformation Diagram:
[1, [2, 3], [4, [5, 6]]]
↓
[1, 2, 3, 4, [5, 6]]
↓
[1, 2, 3, 4, 5, 6]
Before vs After Comparison:
Before (Nested) After (Flattened)
[ [
1, 1,
[2, 3], -----> 2,
[4, [5, 6]] 3,
] 4,
5,
6
]
Top comments (0)