Array Flattening in JavaScript
Understand Array Flattening in JavaScript

Search for a command to run...
Understand Array Flattening in JavaScript

No comments yet. Be the first to comment.
In this series of blogs I have written some interesting concepts related to JavaScript.
Introduction When writing real-world JavaScript applications, extracting values from arrays and objects often becomes repetitive and verbose. Destructuring solves this problem by allowing you to unpac
JavaScript gives us powerful primitives like objects and arrays, and for a long time they were enough to solve most problems. But as applications grew in complexity, certain limitations became clear.

Understanding call(), apply(), and bind() in JavaScript

"this" keyword in JavaScript

Introduction When writing real-world JavaScript applications, extracting values from arrays and objects often becomes repetitive and verbose. Destructuring solves this problem by allowing you to unpac

Arrays are one of the most fundamental data structures in JavaScript. In simple cases, they store values in a single, linear structure. But as applications grow, data often becomes more complex — and that’s where nested arrays come into play.
Nested arrays allow us to represent hierarchical or grouped data. However, working with deeply nested structures can quickly become difficult.
This is where array flattening becomes an essential concept.
Flattening transforms a nested array into a single-level array, making it easier to process, iterate, and manipulate.
A nested array is simply an array that contains other arrays as its elements.
const data = [1, 2, [3, 4], [5, [6, 7]]];
In this example:
The array contains numbers
It also contains arrays inside it
Those arrays can themselves contain more arrays
This creates a multi-level structure, similar to a tree.
Think of it like this:
[1, 2, [3, 4], [5, [6, 7]]]
↓
[5, [6, 7]]
↓
[6, 7]
Each level introduces another layer of depth.
At first glance, nested arrays might seem harmless. But in real-world scenarios, they introduce complexity.
Most array operations in JavaScript — like map, filter, and reduce — work best on flat arrays.
const arr = [[1, 2], [3, 4]];
If you want to process all values uniformly, flattening becomes necessary:
[1, 2, 3, 4]
APIs often return deeply nested JSON structures.
const users = [
["Prakash", "Rahul"],
["Aman", ["Riya", "Neha"]]
];
To extract meaningful data, flattening helps convert it into a usable format.
Flat arrays:
Reduce nested loops
Simplify conditions
Improve readability
Rendering lists in UI frameworks
Data normalization before storing in databases
Processing logs or analytics data
Handling recursive structures like comments or folders
Flattening is not just a function — it’s a way of thinking.
At its core:
“If an element is an array, break it down further. If it’s not, keep it.”
Input:
[1, [2, [3, 4]], 5]
Output:
[1, 2, 3, 4, 5]
Start:
[1, [2, [3, 4]], 5]
Take 1 → keep it
Encounter [2, [3, 4]] → open it
Take 2 → keep it
Encounter [3, 4] → open it
Take 3, 4 → keep both
Take 5 → keep it
Final:
[1, 2, 3, 4, 5]
This mental model is the foundation of all flattening techniques.
There are multiple ways to flatten arrays in JavaScript. Each approach reflects a different way of thinking.
flat() — The Built-in MethodJavaScript provides a built-in method for flattening arrays.
const arr = [1, [2, [3, 4]]];
arr.flat(2);
// [1, 2, 3, 4]
The number passed defines the depth.
For unknown depth:
arr.flat(Infinity);
Clean and readable
No manual logic required
Ideal for everyday usage
Recursion mirrors the structure of nested arrays perfectly.
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;
}
This works because:
Each nested array is treated as a smaller version of the same problem
The function keeps calling itself until no arrays remain
This is similar to how tree traversal works.
reduce()This method uses a more declarative style.
function flatten(arr) {
return arr.reduce((acc, curr) => {
return Array.isArray(curr)
? acc.concat(flatten(curr))
: acc.concat(curr);
}, []);
}
Instead of building step-by-step manually:
You accumulate results
Combine them recursively
This approach is common in functional programming.
Recursion is elegant, but not always ideal for very deep structures.
An alternative is using a stack:
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();
}
Replace recursion with manual control
Use a stack to simulate depth traversal
Not all flattening needs to be complete.
Sometimes you only want to flatten one or two levels.
const arr = [1, [2, [3, 4]]];
arr.flat(1);
// [1, 2, [3, 4]]
This is useful when:
You want partial transformation
You want to preserve some structure
Real-world data is rarely clean.
[1, [], [2, []]]
[1, "text", [true, [null]]]
[[[[[1]]]]]
[1, , [2, , [3]]]
Good implementations handle all of these gracefully.
Different approaches behave differently depending on data size.
Easy to write
May cause stack overflow for very deep arrays
More control
Safer for large data
Optimized internally
Best for most practical use cases
Flattening is more than just an array problem.
It connects to:
Tree traversal
Recursion patterns
Depth-first search
Data transformation pipelines
Understanding flattening deeply strengthens your ability to solve complex problems.
Array flattening might look like a small utility problem, but it teaches an important lesson:
Complex structures can often be simplified by breaking them down step by step.
Once you understand the idea of:
Identifying structure
Decomposing it
Rebuilding it
You unlock a powerful way of thinking that applies far beyond arrays.
I write articles on blog.prakashtsx.com and also post development-related content on: