Array Flatten in Java
Handling Nested Data Like a Pro

In the previous blog, we learned how to work with arrays using methods like map, filter, and reduce. You saw how to transform, filter, and compute data from arrays. But real-world data is not always flat. Sometimes, your data looks like this:
const arr = [1, 2, [3, 4], [5, [6, 7]]];
Now the problem changes. You cannot directly use map or filter properly because the structure is nested. To work with this kind of data, you first need to flatten it.
What Does Flattening Mean?
Flattening means converting a nested array into a single-level array.
const arr = [1, 2, [3, 4]];
const flattened = [1, 2, 3, 4];
Simple idea. But implementation can get tricky depending on depth.
Why Do We Need Flattening?
Real-world data often comes nested:
API responses
tree structures
comments with replies
categories with subcategories
Example:
const comments = [
{ id: 1, replies: [{ id: 2 }, { id: 3 }] }
];
If you want to process all comments, you need to flatten this structure.
Method 1: Array.flat()
JavaScript provides a built-in method called flat.
const arr = [1, 2, [3, 4]];
const result = arr.flat();
console.log(result); // [1, 2, 3, 4]
Depth Parameter
const arr = [1, 2, [3, [4, 5]]];
console.log(arr.flat(1)); // [1, 2, 3, [4, 5]]
console.log(arr.flat(2)); // [1, 2, 3, 4, 5]
Flatten Completely
arr.flat(Infinity);
This flattens all levels.
Limitations of flat()
Not supported in very old browsers
Does shallow flattening per level
Sometimes you need custom control
That’s where manual approaches come in.
Method 2: Using reduce
const arr = [1, 2, [3, 4]];
const flattened = arr.reduce((acc, curr) => {
return acc.concat(curr);
}, []);
console.log(flattened);
Problem with This Approach
This works only for one level.
[1, [2, [3]]]
This will not fully flatten.
Method 3: Recursion (Most Important)
This is the real solution for nested arrays.
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;
}
const arr = [1, [2, [3, 4]]];
console.log(flatten(arr));
Understanding the Recursive Flow
Take this array:
[1, [2, [3]]]
Step by step:
1 → push
[2, [3]] → call function again
2 → push
[3] → call again
3 → push
Final result:
[1, 2, 3]
Mental Model for Recursion
Think of it like peeling layers.
Each time you find an array:
go inside
process it
come back
Method 4: Using Stack (Iterative Approach)
If you want to avoid recursion:
function flatten(arr) {
let stack = [...arr];
let result = [];
while (stack.length) {
let value = stack.pop();
if (Array.isArray(value)) {
stack.push(...value);
} else {
result.push(value);
}
}
return result.reverse();
}
Why This Works
Stack keeps track of elements
Nested arrays are expanded
Values are collected
Real-World Example
const categories = [
{
name: "Electronics",
children: [
{ name: "Phones" },
{ name: "Laptops" }
]
}
];
You may want:
["Electronics", "Phones", "Laptops"]
Flattening helps here.
Common Mistakes
1. Assuming flat() always works
Older environments may not support it.
2. Forgetting depth
arr.flat(1);
Does not fully flatten deeply nested arrays.
3. Incorrect recursion base case
Forgetting to stop recursion properly.
Performance Consideration
flat() is optimized
recursion is readable but may hit call stack limits
iterative approach is safer for very large data
When to Use What
Use
flat()→ when available and simpleUse recursion → for full control
Use stack → for large data
Putting It All Together
function processData(arr) {
return arr
.flat(Infinity)
.filter(n => n % 2 === 0)
.map(n => n * 2);
}
const data = [1, [2, 3], [4, [5, 6]]];
console.log(processData(data));
Final Thought
Flattening arrays is not just about arrays. It is about handling nested data. And in real-world applications, nested data is everywhere. If you understand this concept properly, you can handle complex data structures with confidence.






