Array Flatten in JavaScript

When working with arrays, sometimes we don’t get a simple flat array.
Instead, we get nested arrays.
That means arrays inside arrays.
Example:
const arr = [1, [2, 3], [4, [5, 6]]]
Now this is not a simple array anymore.
It has multiple levels.
So if we want all values in a single list, we need to flatten it.
What are Nested Arrays
A nested array is just an array that contains another array inside it.
Example:
const arr = [1, [2, 3], 4]
Structure looks like:
More complex example:
[1, [2, [3, [4]]]]
Here we have multiple levels.
Why Flattening is Useful
In real programs, nested arrays can make things harder.
For example:
looping becomes complex
accessing values is difficult
data processing becomes messy
Sometimes we just want:
[1, 2, 3, 4, 5, 6]
instead of:
[1, [2, 3], [4, [5, 6]]]
So flattening makes the data easier to work with.
Concept of Flattening
Flattening means:
We remove all nesting and bring everything to a single level.
Flatten Transformation
Approach 1: Using flat()
JavaScript already gives a method called flat().
const arr = [1, [2, 3], [4, [5, 6]]]
const flatArr = arr.flat(2)
console.log(flatArr)
Output:
[1, 2, 3, 4, 5, 6]
Here 2 means how deep we want to flatten.
Approach 2: Using Infinity
If we don’t know the depth, we can use:
const flatArr = arr.flat(Infinity)
This will flatten everything.
Approach 3: Using Recursion
Sometimes in interviews, they expect you to write your own logic.
So let’s think step by step.
We go through each element:
if it is a number → push it
if it is an array → go inside it
Example:
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, [5, 6]]]
console.log(flatten(arr))
Output:
[1, 2, 3, 4, 5, 6]
How to Think About It
The idea is simple:
If value is array --> go deeper
If value is normal --> collect it
This thinking works for any depth.
Nested arrays are common in real world data.
Flattening helps simplify the structure and makes it easier to work with.
JavaScript provides flat() for quick use, but knowing how to solve it manually helps in interviews and deeper understanding.




