Array Flatten in JavaScript: Untangling Nested Data
Learn how to process complex nested arrays, master modern built-in methods, and ace the classic array-flattening interview question.
If you have been following our journey through JavaScript data structures, you already know that arrays are incredibly powerful tools for storing lists of data. (If you need a refresher, check out my previous guides: JavaScript Arrays 101 and JavaScript Arrays: The 7 Methods You Actually Need to Know).
But what happens when the data inside your array is... another array? And what if that array holds even more arrays?
Welcome to the world of nested arrays. While they are great for representing complex relationships, they can be a nightmare to loop through and manipulate. To work with this data effectively, we often need to transform it into a single, straightforward list.
This process is called Array Flattening, and it is one of the most common tasks you will encounter in both real-world web development and technical interviews. Let’s dive in and learn how to untangle our data.
What Are Nested Arrays?
A nested array (often called a multi-dimensional array) is simply an array that contains other arrays as its elements.
Think of it like a set of Russian Matryoshka dolls. You open the outer array, only to find another array inside it.
Visualizing Nested Arrays
Here is how nested arrays look in code, structured by "depth" levels:
// Level 0: A standard, flat array
const flatArray = [1, 2, 3, 4];
// Level 1: An array containing arrays (1 level deep)
const levelOne = [1, [2, 3], 4];
// Level 2: An array inside an array inside an array
const levelTwo = [1, [2, [3, 4]], 5];
Why is Flattening Arrays Useful?
Flattening is the process of removing those inner brackets and bringing all the elements up to the top level, creating one single, continuous array.
Why would we want to do this?
Cleaning API Responses: Sometimes backend APIs return messy, nested lists. If you ask a database for "all users' comments," it might return an array of users, where each user has an array of comments. To display them in a single timeline, you need to flatten the data.
Data Processing: Array methods like
.map()and.filter()work best on flat data. If your data is nested, you have to write complex, nested loops to process it.UI Rendering: If you are building a dropdown menu from a list of categories and sub-categories, flattening makes it infinitely easier to render the items in React or vanilla DOM.
Different Approaches to Flatten Arrays
When it comes to flattening, JavaScript gives us a few different ways to solve the problem, ranging from modern built-in methods to classic algorithmic approaches.
1. The Modern Way: Array.prototype.flat()
Introduced in ES2019, JavaScript finally gave us a built-in method to handle this: .flat().
By default, .flat() will only flatten the array one level deep.
const nested = [1, [2, 3], [4, [5, 6]]];
// Flattens 1 level deep by default
const flatOne = nested.flat();
console.log(flatOne);
// Output: [1, 2, 3, 4, [5, 6]]
Notice how [5, 6] is still nested? If you want to go deeper, you can pass a depth parameter into the method.
// Flattens 2 levels deep
const flatTwo = nested.flat(2);
console.log(flatTwo);
// Output:[1, 2, 3, 4, 5, 6]
Pro Tip: What if you don't know how deep the nesting goes? You can pass Infinity to completely flatten the array regardless of its depth!
const crazyNested = [1, [[[[2]]]], [[3, 4]]];
console.log(crazyNested.flat(Infinity));
// Output: [1, 2, 3, 4]
2. The Functional Way: reduce() and concat()
Before .flat() existed, developers had to write their own flattening logic. A common way to flatten an array exactly one level deep is by combining reduce() with concat().
const nested = [1, [2, 3], [4, 5]];
const flattened = nested.reduce((accumulator, currentValue) => {
return accumulator.concat(currentValue);
},[]);
console.log(flattened); // Output: [1, 2, 3, 4, 5]
How it works: We start with an empty array []. We loop through the nested array. If the current value is a number, concat pushes it in. If the current value is an array ([2, 3]), concat unpacks it and merges its items into the accumulator.
3. The Interview Favorite: Custom Recursive Flatten
This is where problem-solving thinking comes in. Interviewers love to ask you to flatten an array without using the built-in .flat() method. They want to see if you can handle infinite nesting using Recursion (a function that calls itself).
Step-by-step problem-solving thinking:
We need a new, empty array to store our final results.
We need to loop through the given array.
For every item, we ask: "Are you an array?"
If No, just push the item into our result array.
If Yes, we need to flatten that inner array before pushing its items. How do we flatten it? By running it through our function again!
Here is the code:
function customFlatten(arr) {
let result =[];
for (let i = 0; i < arr.length; i++) {
// Check if the current item is an array
if (Array.isArray(arr[i])) {
// If it is, recursively flatten it, then merge it into the result
result = result.concat(customFlatten(arr[i]));
} else {
// If it's not an array, just push the value
result.push(arr[i]);
}
}
return result;
}
const deeplyNested = [1, [2,[3, [4, 5]]], 6];
console.log(customFlatten(deeplyNested));
// Output: [1, 2, 3, 4, 5, 6]
Common Interview Scenarios
If you are interviewing for a Frontend or Fullstack role, be prepared for this topic. Here is how interviewers usually frame it:
"Write a polyfill for Array.prototype.flat()." Translation: Write a custom function that does exactly what
.flat()does, usually expecting the recursive approach shown above. They might also ask you to implement thedepthparameter manually!"Filter out all the odd numbers from this nested array." The trap: Trying to filter while the array is still nested is a nightmare. The solution: Flatten the array completely first using
.flat(Infinity), and then run.filter(num => num % 2 === 0)on the clean, flat array."Can you flatten this without creating a new array?" Translation: The interviewer wants to test your knowledge of mutating arrays in place (using
.splice()). This is an advanced edge case, but good to think about!
Summary
Nested arrays don't have to be intimidating. By understanding the concept of flattening, you can transform chaotic, multi-layered data into clean, manageable lists.
In your day-to-day web development, Array.prototype.flat(Infinity) will be your best friend. But when interview season comes around, make sure you understand the recursive approach. It demonstrates that you don't just know how to use JavaScript's built-in tools, but that you actually understand the logic behind them.

