Array Flatten in JavaScript

While working with arrays in JavaScript, we often encounter situations where data is not in a simple, single-level structure. Instead, arrays can contain other arrays, creating what we call nested arrays.
At first glance, these nested arrays may seem easy to handle—but when you try to loop through them, filter data, or perform operations, things can quickly become complicated.
const categories = [
"Electronics",
["Mobiles", "Laptops"],
["Clothing", ["Men", "Women"]]
];
Now, imagine you want all values in a single array like this:
["Electronics", "Mobiles", "Laptops", "Clothing", "Men", "Women"]
Working with this flat structure is much easier—you can loop, search, sort, or manipulate data without worrying about nested levels.
This is where the concept of array flattening comes in.
Array flattening is the process of converting a nested array into a one-dimensional array, making it easier to work with and process data efficiently.
What are nested arrays?
A nested array is simply an array that contains one or more arrays inside it.
In JavaScript, arrays can store any type of value—including other arrays. This allows developers to represent complex or hierarchical data structures.
Simple Example
const numbers = [1, 2, [3, 4], 5];
Here:
1,2, and5are normal elements[3, 4]is a nested array inside the main array
Deeper Nested Example
const data = [1, [2, [3, [4]]]];
This is called multi-level nesting, where arrays are nested inside arrays multiple times.
Visual Representation
Think of nested arrays like boxes inside boxes:
[
1,
[
2,
[
3,
[ 4 ]
]
]
]
Each level adds complexity when trying to access or process the values.
Accessing Nested Elements
To access values inside nested arrays, you need multiple indexes:
const arr = [1, [2, [3]]];
console.log(arr[1]); // [2, [3]]
console.log(arr[1][1]); // [3]
console.log(arr[1][1][0]); // 3
As you can see, deeper nesting makes access more complicated and less readable.
Nested arrays are powerful for structuring complex data, but they can make operations like:
looping
searching
filtering
more difficult to implement.
Why is flattening arrays useful?
When working with nested arrays, performing common operations becomes harder because data is spread across multiple levels. Flattening simplifies the structure and makes your code cleaner and easier to maintain.
Flattening transforms complex hierarchical data into a simple linear structure, making it easier to read, process, and manipulate.
Here are some key reasons why flattening arrays is useful:
1. Easier Iteration
Looping through a nested array requires multiple loops or recursion. A flat array can be handled with a single loop.
Nested array
const arr = [1, [2, 3], [4, [5]]];
To iterate this, you must check if each element is an array.
Flattened array
[1, 2, 3, 4, 5]
Now a simple loop works:
arr.forEach(num => console.log(num));
2. Simplifies Searching
Searching inside nested arrays requires checking every level.
const tags = ["js", ["react", "node"], ["css", ["tailwind"]]];
If flattened:
["js", "react", "node", "css", "tailwind"]
You can directly use:
tags.includes("node");
3. Makes Data Transformation Easy
Operations like map, filter, and reduce work best on flat structures.
Without flattening
[1, [2, 3]].map(x => x * 2); // ❌ won't work properly
After flattening
[1, 2, 3].map(x => x * 2); // ✅ [2, 4, 6]
4. Useful in Real-World Scenarios
Flattening is commonly needed when working with:
API responses
Category trees
Comment threads
File system structures
Menu navigation data
Example API response:
const comments = [
{ id: 1, replies: [{ id: 2 }, { id: 3 }] }
];
Flattening helps convert nested replies into a single list.
You are essentially removing all inner levels and bringing every value to the top.
Concept of flattening arrays
Concept of flattening arrays
The idea behind array flattening is simple:
Take every element from all nested levels and move it into a single top-level array.
Instead of keeping arrays inside arrays, we extract values one by one, no matter how deeply nested they are.
Consider this nested array:
const arr = [1, [2, 3], [4, [5, 6]]];
If we flatten it, we remove the inner structure and bring everything to one level:
[1, 2, 3, 4, 5, 6]
Step-by-Step Flattening
Let's break down how flattening works conceptually.
Start with:
[1, [2, 3], [4, [5, 6]]]
Step 1: Take 1 → add to result
Result: [1]
Step 2: Encounter [2, 3] → open it and take values
Result: [1, 2, 3]
Step 3: Encounter [4, [5, 6]] → open it
Result: [1, 2, 3, 4]
Step 4: Encounter [5, 6] → open again
Result: [1, 2, 3, 4, 5, 6]
Final flattened array:
[1, 2, 3, 4, 5, 6]
You can think of flattening as:
📦 Boxes inside boxes → opened completely
➡️ All items placed in one single row
While flattening:
If the element is not an array → add directly
If element is an array → go inside it and repeat the process
This repeated process is what makes flattening work for any level of nesting.
Different Approaches to Flatten Arrays
There are multiple ways to flatten arrays in JavaScript. Each approach helps you understand problem-solving from a different perspective.
We’ll go from built-in method → logic-based solutions → interview-style approaches.
1. Using flat() (Built-in Method)
JavaScript provides a built-in method called flat() Which is the easiest way to flatten arrays?
const arr = [1, [2, 3], [4, [5, 6]]];
const flattened = arr.flat();
console.log(flattened);
Output:
[1, 2, 3, 4, [5, 6]]
By default, it flattens only one level.
To flatten deeper levels, you can pass depth:
const flattened = arr.flat(2);
Output:
[1, 2, 3, 4, 5, 6]
To flatten any level, use:
arr.flat(Infinity);
This is the simplest and most readable approach.
2. Using Recursion (Most Common Interview Approach)
This is the most popular approach asked in interviews.
The idea:
Loop through the array
If element is an array → flatten again
Else → push to result
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, 6]]];
console.log(flattenArray(arr));
Output:
[1, 2, 3, 4, 5, 6]
This approach works for any nesting depth.
3. Using reduce()
This is a more functional programming style.
function flattenArray(arr) {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
return acc.concat(flattenArray(item));
}
return acc.concat(item);
}, []);
}
This works the same as recursion, but uses reduce.
4. Using Stack (Without Recursion)
This approach avoids recursion and is useful for large arrays.
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();
}
This is considered a more advanced interview solution.
Common Interview Scenarios
Array flattening is a very common topic in JavaScript interviews. Instead of asking directly, interviewers often twist the problem to test your understanding of recursion, iteration, and problem-solving.
Here are some common variations you may encounter.
1. Flatten Array Completely (Basic Version)
Question:
Flatten a nested array of unknown depth.
const arr = [1, [2, [3, [4]], 5]];
Expected Output:
[1, 2, 3, 4, 5]
These tests:
Recursion understanding
Handling unknown nesting levels
2. Flatten Only One Level
Sometimes interviewers ask to flatten only one level.
const arr = [1, [2, 3], [4, [5]]];
Expected Output:
[1, 2, 3, 4, [5]]
This checks whether you understand controlled flattening depth.
3. Flatten Array With Depth
You may be asked to implement your own version of flat(depth).
Example:
flatten([1, [2, [3, [4]]]], 2);
Expected Output:
[1, 2, 3, [4]]
These tests:
Recursion with conditions
Depth tracking logic
4. Flatten Mixed Data Types
Arrays may contain different types of values.
const arr = [1, "hello", [true, [null, 5]]];
Expected Output:
[1, "hello", true, null, 5]
This checks:
Generic handling
No assumptions about data types
5. Flatten Without Using Built-in Methods
Interviewers often restrict:
❌ Do not use:
flat()flatMap()
They want to see your logic implementation.
6. Large Nested Array (Performance Focus)
Sometimes the focus is performance.
const arr = [[[[[1]]]], 2, [[[3]]]];
Here they may ask:
Avoid a recursion stack overflow
Use an iterative approach (stack)
Interview Tip
When asked to flatten arrays, think step-by-step:
Check if the element is an array
If yes → go deeper
If not → store result
Repeat until complete
This pattern works for most flattening problems.
Conclusion
Array flattening helps convert nested arrays into a single-level structure, making data easier to loop, search, and manipulate. Understanding different approaches—like built-in methods, recursion, and iterative solutions—improves both coding skills and problem-solving ability. Mastering this concept is useful for real-world applications and common JavaScript interview questions.



