Flatten a Nested Array in JavaScript
Imagine you have a basket of fruits packed into smaller boxes inside a bigger box. If you want to access all the fruits easily, you'd want to take them out and lay them in one straight line. Similarly, flattening a nested array in JavaScript means taking values from multiple inner arrays and placing them in a single-level array.
Whether you're building a shopping list, transforming API responses, or simply organizing data more cleanly, flattening arrays is a must-have skill in your JavaScript toolbox. Let's walk through a few different techniques to flatten arrays—each designed with simplicity and clarity in mind.
Method 1: Using Array.prototype.flat()
The flat()
method is the most straightforward and modern way to flatten arrays. It’s clean, simple, and beginner-friendly. By default, it only flattens one level deep, but you can pass an argument to flatten deeper levels.
const fruits = ["apple", ["banana", "cherry"], ["date", ["elderberry"]]];
const flattened = fruits.flat(2);
console.log(flattened);
["apple", "banana", "cherry", "date", "elderberry"]
Method 2: Using Recursion
When the array is deeply nested and you want full control over how it's flattened, a recursive approach is ideal. Recursion allows you to explore and flatten every level of nesting, no matter how deep it goes.
function flattenArray(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flattenArray(val)) : acc.concat(val), []);
}
const fruits = ["apple", ["banana", ["cherry", ["date"]]], "elderberry"];
const flattened = flattenArray(fruits);
console.log(flattened);
["apple", "banana", "cherry", "date", "elderberry"]
Method 3: Using reduce()
with a Stack
If recursion feels too abstract or if you’re dealing with performance-sensitive environments, you can use an iterative stack-based approach. This method unfolds the array by pushing items to a stack and processing them one by one.
function flattenWithStack(arr) {
const stack = [...arr];
const result = [];
while (stack.length) {
const next = stack.pop();
if (Array.isArray(next)) {
stack.push(...next);
} else {
result.push(next);
}
}
return result.reverse();
}
const fruits = ["apple", ["banana", ["cherry"]], "date"];
const flattened = flattenWithStack(fruits);
console.log(flattened);
["apple", "banana", "cherry", "date"]
Which Method Is Right for You?
If you're just getting started, use flat()
. It’s readable, concise, and perfectly suited for small-to-medium tasks. If you're dealing with highly unpredictable or deeply nested data, recursive flattening gives you the flexibility to handle anything. The stack-based version is an excellent alternative if you want to avoid recursion for memory or control reasons.
Final Thoughts
Mastering the art of flattening arrays in JavaScript isn't just a technical skill—it's a thinking tool. It helps you manipulate data elegantly, transform nested structures, and handle real-world problems like parsing JSON responses or reshaping UI lists.
Whether you use flat()
for its elegance, recursion for its power, or reduce()
for hands-on logic, you now have multiple lenses to look at the same problem—and solve it with clarity. Keep practicing, and soon, these patterns will become second nature in your development journey.
Comments
Loading comments...