Flattening an Array in JavaScript

After coming back from sabzi mandi. You have one massive jhola (cloth bag). You look inside, and there is a plastic bag of potatoes. Dig deeper, and inside a bag of dhaniya, the vendor had put packet of green chilies.
In JavaScript, this bag inside a bag inside a bag situation is exactly what we call a Nested Array. Lets break down how to unpack all those vegetables into one flat array.
What are Nested Arrays ?
A nested array (multidimensional array) is simply an array where one or more elements are alslo arrays.
//"Mandi Bag" Example
const mandiBag = ["Potatoes", ["Onions", "Tomatoes"], ["Coriander", ["Green Chilies"]]];
Here, mandiBag has a levels of nesting. Green chillies is two levels deep.
Why Flattening Arrays is Useful
If we want to count all the individual vegetables we brought, we can not just count the bags. We have to take everything out and lay it flat. In programming, you flatten arrays for similar reasons:
Simplifying Data: APIs usually return deeply nested JSON data. Flattening helps convert this complex structure into a simple.
Data Processing: Before applying methods like
map(),filter(), orreduce()across all elements, we need them in a single line.UI Rendering: For example, React prefer flat lists to render components efficiently.
The Concept of Flattening
Flattening is process of reducing the dimensionality of an array. We are removing the inner brackets [] and merging all the items into the parent array.
If we flatten mandiBag completely, it goes from this:["Potatoes", ["Onions", "Tomatoes"], ["Coriander", ["Green Chilies"]]]
To this: ["Potatoes", "Onions", "Tomatoes", "Coriander", "Green Chilies"]
Different Approaches to Flatten Arrays
There are several ways to dothis, from modern shortcuts to classic problem-solving algorithms.
1. Array.prototype.flat()
Introduced in ES2019, JavaScript now has a built-in method just for this. By default, it only flattens one level deep.
const numbers = [1, [2, 3], [[4, 5]]];
// Flattens 1 level (default)
console.log(numbers.flat()); // Output: [1, 2, 3, [4, 5]]
// Flattens completely
console.log(numbers.flat(Infinity)); // Output: [1, 2, 3, 4, 5]
2. Recursion
Interviewers love to say, "write it without using .flat()"
The Strategy:
Create an empty "counter" (a new array).
Go through the main bag item by item.
If the item is a vegetable (a regular value), put it on the counter.
If the item is another bag (an array), recursively apply the same process to unpack it.
function flattenArray(arr) {
let result = [];
for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
// If it is an array, unpack it and join it
result = result.concat(flattenArray(arr[i]));
} else {
// If it is a value, push it
result.push(arr[i]);
}
}
return result;
}
const nestedArray = [1, [2, [3, 4], 5]];
console.log(flattenArray(nestedArray)); // Output: [1, 2, 3, 4, 5]
3. Iterative with a Stack
Sometimes, recursion can cause a error if array is very deep. A robust, iterative approach uses a Stack.
function flattenWithStack(arr) {
const stack = [...arr];
const result = [];
while (stack.length) { // Pop the top item
const next = stack.pop();
if (Array.isArray(next)) {
// If it's an array, push its items back onto the stack
stack.push(...next);
} else {
// If not, it goes to the result
result.push(next);
}
}
// The stack processes backwards, reversing it at end
return result.reverse();
}
Common Interview Scenarios
When you walk into a JavaScript interview, keep these variations in mind:
"Flatten up to 'N' depth": They might ask you to write a custom flat function that takes a
depthparameter (just like the built-in one). You'll need to pass the depth counter down in your recursive function and subtract 1 each time."Handle empty slots": The built-in
.flat()automatically removes empty slots in arrays (e.g.,[1, 2, , 4]). Interviewers might ask if your custom function handles this."Type checking": Always use
Array.isArray(element)to check if something is an array.typeof elementwill return"object", which can cause bugs if you have standard objects{}mixed in your data!
By mastering these approaches, you'll be able to organize even the messiest data structures.
Thanks for reading.
