Array Flatten in JavaScript
Introduction
In JavaScript, arrays can sometimes contain other arrays inside them. These are called nested arrays. Working with nested arrays can be tricky, so we often need to convert them into a single-level array. This process is called array flattening.
What Are Nested Arrays?
A nested array is an array inside another array.
Example
const arr = [1, 2, [3, 4], [5, 6]];
Here:
[3, 4]and[5, 6]are inside the main arraySo this is a nested array
Why Flattening Arrays Is Useful
Flattening helps when:
You need a simple list of values
You want to loop through all elements easily
You are working with APIs that return nested data
You want to perform operations like sum, filter, map
Concept of Flattening Arrays
Flattening means converting:
[1, 2, [3, 4], [5, 6]]
Into:
[1, 2, 3, 4, 5, 6]
Step-by-Step Understanding
Nested Structure
[1, [2, [3, 4]]]
Flatten Step by Step
Step 1: [1, 2, [3, 4]]
Step 2: [1, 2, 3, 4]
Different Approaches to Flatten Arrays
1. Using flat() Method (Easy Way)
JavaScript provides a built-in method.
const arr = [1, 2, [3, 4]];
const result = arr.flat();
console.log(result);
Output:
[1, 2, 3, 4]
For deeper nesting:
arr.flat(Infinity);
2. Using Loop (Basic Logic)
const arr = [1, [2, 3], 4];
let result = [];
for (let item of arr) {
if (Array.isArray(item)) {
result = result.concat(item);
} else {
result.push(item);
}
}
console.log(result);
3. Using Recursion (Important for Interviews)
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;
}
console.log(flatten([1, [2, [3, 4]]]));
4. Using reduce()
const arr = [1, [2, [3, 4]]];
const result = arr.reduce((acc, item) => {
return acc.concat(Array.isArray(item) ? result = flatten(item) : item);
}, []);
console.log(result);
Common Interview Scenarios
Flatten array without using
flat()Flatten deeply nested arrays
Handle mixed data types
Optimize recursion
Example question: "Write a function to flatten an array of any depth."
Visual Diagram Ideas
Nested Array Structure
[1
[2
[3, 4]
]
]
Flatten Transformation
Nested → [1, [2, [3, 4]]]
Flat → [1, 2, 3, 4]
Problem Solving Thinking
When solving flatten problems:
Check if element is array
If yes → go deeper
If no → add to result
Repeat until all elements are processed
Conclusion
Array flattening is an important concept in JavaScript. It helps you simplify complex data structures and is commonly asked in interviews. Learning different approaches like flat(), loops, and recursion will make your problem-solving skills stronger.