Array Flatten in JavaScript
Understanding Nested Data and Simplifying Structures

Software engineer passionate about tech, innovation & research. I explore, build, and share insights on coding, systems, and emerging technologies.
Introduction
Working with arrays is a core part of JavaScript development. As applications grow in complexity, data often comes in nested structures—arrays within arrays. While this structure is useful for organizing data, it can make processing and analysis more difficult.
Array flattening is a technique used to simplify such structures by converting a nested array into a single-level array. This document explains the concept in depth, covering definitions, use cases, approaches, and problem-solving strategies.
What Are Nested Arrays
A nested array is an array that contains other arrays as its elements.
Example
const data = [10, [20, 30], [40, [50, 60]]];
Explanation
10is a primitive value[20, 30]is a nested array[40, [50, 60]]is a nested array that contains another nested array
This creates a multi-level structure where elements are not all at the same depth.
Visual Representation
Main Array
│
├── 10
├── [20, 30]
│ ├── 20
│ └── 30
└── [40, [50, 60]]
├── 40
└── [50, 60]
├── 50
└── 60
Why Flattening Arrays Is Useful
Nested arrays can complicate common operations such as iteration, aggregation, and searching.
Problems with Nested Arrays
Requires multiple loops or recursion
Harder to apply array methods like
map,reduce, orfilterIncreases code complexity
Benefits of Flattening
Simplifies data structure
Enables direct use of array utilities
Improves readability and maintainability
Example Scenario
const marks = [[85, 90], [78], [92, 88]];
If you want to:
Calculate total marks
Find the highest score
Compute average
Flattened version:
[85, 90, 78, 92, 88]
Now operations become straightforward.
Concept of Flattening Arrays
Flattening means removing nested levels and bringing all values into a single array.
Step-by-Step Example
const input = [5, [6, 7], 8];
Step 1: Initialize Result
[]
Step 2: Read 5
Not an array
Add to result
[5]
Step 3: Read [6, 7]
It is an array
Extract elements
[5, 6, 7]
Step 4: Read 8
Not an array
Add to result
[5, 6, 7, 8]
Final Output
[5, 6, 7, 8]
Transformation Diagram
Before Flattening:
[5, [6, 7], 8]
After Flattening:
[5, 6, 7, 8]
Different Approaches to Flatten Arrays
1. Using flat() Method
The flat() method is a built-in JavaScript function for flattening arrays.
Example
const values = [1, [2, 3], 4];
const result = values.flat();
console.log(result); // [1, 2, 3, 4]
Behavior
Default depth is 1
Only removes one level of nesting
2. Using flat(depth)
For deeper nested arrays, specify the depth.
Example
const values = [1, [2, [3, [4]]]];
const result = values.flat(3);
console.log(result); // [1, 2, 3, 4]
Depth Explanation
flat(1)→ removes one levelflat(2)→ removes two levelsflat(n)→ removes n levels
3. Using flat(Infinity)
When nesting depth is unknown, use Infinity.
Example
const values = [1, [2, [3, [4, [5]]]]];
const result = values.flat(Infinity);
console.log(result); // [1, 2, 3, 4, 5]
4. Using Recursion
A manual approach using recursion provides full control.
Example
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 input = [1, [2, [3, 4]], 5];
console.log(flattenArray(input)); // [1, 2, 3, 4, 5]
Key Idea
Check if element is an array
If yes, recursively flatten it
If no, add directly
5. Using reduce()
A functional programming approach.
Example
const flatten = (arr) => {
return arr.reduce((acc, item) => {
if (Array.isArray(item)) {
return acc.concat(flatten(item));
}
return acc.concat(item);
}, []);
};
const input = [2, [4, [6, 8]], 10];
console.log(flatten(input)); // [2, 4, 6, 8, 10]
Advantage
Clean and expressive
Combines recursion with accumulation
Common Interview Scenarios
1. Flatten Without Using flat()
Interviewers often ask for a manual implementation.
Focus:
Recursion
Loop-based solution
2. Flatten to Specific Depth
Example:
flatten([1, [2, [3]]], 1) → [1, 2, [3]]
Requires:
Depth tracking
Conditional recursion
3. Handle Mixed Data Types
const input = [1, ['a', [true, [null]]]];
Expected:
[1, 'a', true, null]
4. Large Data Optimization
Avoid excessive recursion depth
Use iterative approaches if needed
5. Real-World Data Transformation
Example:
const responses = [
{ data: [1, 2] },
{ data: [3, 4] }
];
Flatten:
[1, 2, 3, 4]
Problem-Solving Mindset for Flattening
1. Identify the Structure
Is it single-level or multi-level?
How deeply nested is it?
2. Decide the Strategy
Use
flat()for simple casesUse recursion for control
Use
reduce()for functional style
3. Think in Terms of Expansion
For each element:
If not array → keep it
If array → expand it
4. Break the Problem Down
Instead of solving the entire array:
Focus on one element at a time
Apply the same logic recursively
5. Visualize the Process
Always imagine:
Opening nested layers
Collecting values into one container
Example Thinking
Input:
[3, [6, [9]]]
Thinking:
3 → keep
[6, [9]] → open
6 → keep
[9] → open
9 → keep
Output:
[3, 6, 9]
Conclusion
Array flattening is an essential concept in JavaScript for simplifying complex data structures. Whether using built-in methods like flat() or implementing custom recursive solutions, understanding how flattening works improves both problem-solving ability and code efficiency.
Mastering this concept is particularly valuable for interviews and real-world applications where data transformation is a frequent requirement.




