How to Flatten a Nested Array in JavaScript
Flatten a nested array in JavaScript with Array.prototype.flat(), including how to flatten to any depth and a manual recursive alternative.
Published September 16, 2026
The built-in Array.prototype.flat() method flattens nested arrays into a single-level array up to a given depth.
[1, [2, 3], [4, [5, 6]]].flat(Infinity)
// [1, 2, 3, 4, 5, 6]Steps
- Call .flat(depth) on the array, where depth is how many levels of nesting to flatten
- Pass Infinity as the depth to flatten arbitrarily deep nesting in one call
How it works
flat() returns a new array; it does not mutate the original. Without an argument, it defaults to a depth of 1, flattening only the first level of nested arrays.
Things to watch for
- flat() is supported in all modern browsers and Node 11+; for older environments use a recursive reduce() implementation instead
- flatMap() combines map() and a flat(1) in one pass and is often faster when you're transforming and flattening at the same time
FAQ
How do I flatten and map in one step?
Use array.flatMap(fn) — it runs fn over each element and flattens the result by one level, avoiding a separate .map().flat(1) call.