Flattening Arrays in JavaScript: The Smart, Built-In Way
If you’ve ever dealt with arrays in JavaScript, chances are you’ve stumbled upon nested arrays—arrays that contain other arrays. And when it comes time to process or display that data, you’ll often need to flatten them into a single-level array.
Good news: JavaScript has a built-in, elegant solution to flatten arrays without third-party libraries like Lodash or manual loops. It’s called .flat()
.
🧠 What is Flattening?
Flattening means transforming a nested array like this:
[1, [2, [3, [4]]]]
Into this:
[1, 2, 3, 4]
It simplifies data handling, especially when working with APIs, spreadsheet exports, or multi-level form data.
🔧 The Array.prototype.flat()
Method
Introduced in ES2019, the .flat()
method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
✅ Basic Usage
const nested = [1, [2, 3], 4];
const flat = nested.flat();
console.log(flat);
// Output: [1, 2, 3, 4]
By default, .flat()
goes 1 level deep. That works great for simple structures, but what about more deeply nested arrays?
🔁 Deep Flattening with .flat(Infinity)
When you don’t know how deeply your arrays are nested—or they’re nested at multiple levels—you can pass Infinity
as the depth:
const deeplyNested = [1, [2, [3, [4]]]];
const fullyFlat = deeplyNested.flat(Infinity);
console.log(fullyFlat);
// Output: [1, 2, 3, 4]
Tip: Always use .flat(Infinity)
when dealing with unpredictable data sources like JSON from APIs or databases.
⚠️ Gotchas and Considerations
Here are a few things to keep in mind when using .flat()
:
- Works only in modern browsers and Node.js versions (>= 11). If you support legacy environments, consider polyfills or a custom recursive function.
Sparse arrays are preserved—empty slots become undefined
.
const arr = [1, , 3];
arr.flat(); // [1, undefined, 3]
It does not mutate the original array.
const arr = [1, [2]];
arr.flat(); // returns new array, does NOT change `arr`
🛠️ Bonus: Use with map()
+ flat()
(a.k.a. flatMap()
)
Sometimes, you want to map and flatten at the same time. That’s where flatMap()
shines:
const data = [1, 2, 3];
const result = data.flatMap(x => [x, x * 2]);
console.log(result);
// Output: [1, 2, 2, 4, 3, 6]
It’s cleaner, faster, and often more expressive.
🧩 Alternative for Older Browsers
If you need to support environments without .flat()
, here’s a simple recursive function:
function flatten(arr) {
return arr.reduce((acc, val) =>
Array.isArray(val) ? acc.concat(flatten(val)) : acc.concat(val), []);
}
But again, if you can use .flat()
, prefer the native method—it’s faster and more readable.
📌 Summary
- Use
.flat()
to flatten arrays one level deep. - Use
.flat(Infinity)
to deeply flatten nested arrays. - Combine
.map()
+.flat()
usingflatMap()
for powerful transformations. - Be mindful of browser support and performance in large datasets.
🚀 Finally
JavaScript’s .flat()
method is a perfect example of how the language continues to evolve to make our lives easier. Instead of reaching for heavy libraries or writing verbose recursive functions, now we can handle nested arrays with a single, expressive line of code.
Whether you’re dealing with user data, DOM structures, or API responses, mastering .flat()
can seriously clean up your code and boost maintainability.
Comments ()