One data grid for JavaScript, React, Vue & Angular. Sorting, filtering, virtualization, pinning, and CSV export included. Early access $199 $349 → [Get it now]

How to flatten a nested array in JavaScript

Flattening nested arrays is crucial when working with hierarchical data structures, processing API responses with nested arrays, or simplifying complex data for easier manipulation in JavaScript applications. As the creator of CoreUI, I’ve implemented array flattening in components like tree navigation, nested menu systems, and data aggregation features where multi-level arrays need to be converted into flat structures. From my extensive expertise, the most modern and efficient solution is using the ES2019 flat() method, which handles nested arrays elegantly. This approach is clean, intuitive, and provides excellent control over the flattening depth.

Use the flat() method to convert nested arrays into a single-level array.

const nested = [1, [2, 3], [4, [5, 6]]]
const flattened = nested.flat()
// Result: [1, 2, 3, 4, [5, 6]]

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. By default, it flattens one level deep. In this example, nested.flat() converts [1, [2, 3], [4, [5, 6]]] to [1, 2, 3, 4, [5, 6]], flattening the first level but leaving the deeper nested array [5, 6] intact. To flatten all levels completely, use nested.flat(Infinity), or specify a number for exact depth control like nested.flat(2).

Best Practice Note:

This is the same approach we use in CoreUI components for processing nested navigation data and flattening hierarchical configurations, such as the Sidebar navigation tree. For older browser support, use alternatives like [].concat(...array) for one level or recursive solutions for deeper nesting. The flat() method is supported in all modern browsers and provides the cleanest syntax for array flattening operations.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.
How to Merge Objects in JavaScript
How to Merge Objects in JavaScript

How to round a number to two decimal places in JavaScript
How to round a number to two decimal places in JavaScript

How to check if a string is a number in JavaScript
How to check if a string is a number in JavaScript

How to check if an array is empty in JavaScript?
How to check if an array is empty in JavaScript?