Array Flatten in JavaScript

Intro of some weird arrays
Ever opened a gift only to find a smaller box inside? And then another box inside that one? While that might be a cruel prank on your birthday, in the world of JavaScript, we call that a Nested Array.
What are Nested Arrays?
A nested array (or a multi-dimensional array) is simply an array that contains other arrays as its elements. It’s like Inception, but instead of dreams, it’s data.
[1, [2, 3], [4, [5, 6]]]
The Developer Joke: Why did the nested array break up with the flat array? Because it needed more "depth" in the relationship. (I'll see myself out.) I wonder if AI would do better...
Why is Flattening Useful?
Why do we care about making things flat?
Simplicity: It’s much easier to map, filter, or reduce a single list than a "box within a box."
API Consistency: Sometimes APIs send data in weird shapes, and you need a clean list to display in your UI.
Searchability: Finding "5" is easier in
[1, 2, 3, 4, 5]than in[[[[5]]]].
Different Approaches to Flattening
There are several ways to tackle this, depending on how deep the "rabbit hole" goes. We could use some built-in methods or opt for some handmade ones, maybe using one or two of other kinds to achieve the output we desire. I think a table would do fine here.
| Method | Best For... | Complexity |
|---|---|---|
.flat() |
Quick fixes (ES2019+) | Super Easy |
| Recursion | Deeply nested, unknown depths | Intellectual Flex |
reduce() + concat() |
Older environments | Classic |
Flat or .flat()
So here's how the basic .flat() works. It's simple, intuitive and kind of esoteric.
const nested = [1, [2, 3], [4, [5, 6]]];
// Flattening one level deep (default)
const shallow = nested.flat();
// Output: [1, 2, 3, 4, [5, 6]]
// Flattening ALL levels deep
const completelyFlat = nested.flat(Infinity);
// Output: [1, 2, 3, 4, 5, 6]
we simply use an inbuilt prototype .flat method and pass the argument that determines till what point deep are we going to flatten the array.
Recursive Approach
So the recursive one is not as intuitive or simple either but interviewers want you to know it so here it goes:
function flattenDeep(arr) {
let result = [];
arr.forEach(item => {
if (Array.isArray(item)) {
// If it's an array, dive deeper!
result = result.concat(flattenDeep(item));
} else {
// If it's just a value, grab it!
result.push(item);
}
});
return result;
}
const deeplyNested = [1, [2, [3, [4, 5]]]];
console.log(flattenDeep(deeplyNested)); // [1, 2, 3, 4, 5]
reduce() + concat()
Here is our frugality at work in full swing. We use reduce() to iterate over each of the elements, element or array and then gather them in the acc. Here is the code that helps understand the workings better.
const nested = [1, [2, 3], [4, 5]];
const flat = nested.reduce((acc, val) => {
return acc.concat(Array.isArray(val) ? val : [val]);
}, []);
console.log(flat); // [1, 2, 3, 4, 5]
This approach demands the knowledge of both reduce() and concat() alike.
The "Problem-Solving" Mindset: Step-by-Step
When an interviewer asks you to flatten an array, they don't just want the code; they want to see how you think. Let's use the Recursive Approach as our mental model:
The Base Case: Look at the current item. Is it a number? Great! Keep it.
The Recursive Step: Is the item another array?
- If yes, dive inside that array and repeat Step 1.
The Collection: Gather all those individual numbers into a brand-new, single-level array.
The Logic Flow:
Input:
[1, [2, 3]]Check
1: It's a number. Result:[1]Check
[2, 3]: It's an array!Check
2: Number. Add to result:[1, 2]Check
3: Number. Add to result:[1, 2, 3]
Output:
[1, 2, 3]
Remember to explain the code to them all the way throughout, they appreciate that.
Common Interview Scenarios
Here are some scenarios you might encounter in your interviews:
"Flatten it without using .flat()": They want to see if you understand recursion.
"Flatten to a specific depth": Can you flatten it only 2 levels deep but leave the 3rd level alone?
"Performance check": What happens if the array has 1,000,000 items? (Hint: Watch out for stack overflow with recursion!)
Pro-Tips & Suggestions
Know your tools: If you’re using modern JavaScript,
array.flat(Infinity)is your best friend. It flattens everything regardless of depth!Don't over-engineer: If you know the data is only one level deep, don't write a 20-line recursive function. Use
[].concat(...myArray).Stay calm: If you get stuck in a nested loop during an interview, just remember: it's just arrays all the way down.
Conclusion
Array flattening is important regarding both development and DSA aspect. So, it's kind of inevitable when it comes to learning it. Cheerios.


