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
Use Array.prototype.flat() to turn a nested array into a single-level array. Pass a depth number, or Infinity to flatten everything.
The concept
flat(depth) walks the array and replaces each nested array with its elements, going depth levels deep. The default depth is 1, so only one layer is removed.
flatMap() combines map() and flat(1) in a single pass, which is handy when each item maps to several results.
Flattening one level at a time
Practical examples
Flatten completely
[1, [2, [3, [4]]]].flat(Infinity) // [1, 2, 3, 4]flatMap for one-to-many
Split every sentence into words and get one flat list.
['a b', 'c d'].flatMap(s => s.split(' ')) // ['a','b','c','d']Recursive fallback for old browsers
const flatten = (arr) =>
arr.reduce((acc, v) => acc.concat(Array.isArray(v) ? flatten(v) : v), [])Common mistakes
- Calling flat() and expecting deep flattening — the default depth is 1.
- Using flatMap when you need to go deeper than one level; it only flattens one.
- Forgetting flat() also removes empty slots in sparse arrays.
Key takeaways
- flat(Infinity) flattens any depth.
- flatMap = map + flat(1).
- Write a recursive reduce only if you must support very old runtimes.
FAQ
Does flat() change the original array?
No, it returns a new array and leaves the original untouched.
Is flat() supported everywhere?
All modern browsers and Node 11+. Use the recursive reduce version for older environments.