How to Flatten an Array in JavaScript
Turning nested arrays into one flat array with flat and flatMap.
There are times when you end up with an array of arrays, like a list of tags for
every post or the results of several API calls. What you really want is one flat
list. JavaScript now has a built in method for this called flat.
The flat() method creates a new array with all of the nested arrays merged
into it, up to the depth you give it.
Using flat()
By default flat goes one level deep:
const tags = [["js", "react"], ["css"], ["html", "a11y"]]console.log(tags.flat())// ["js", "react", "css", "html", "a11y"]
Like map and filter, it returns a new array and leaves the original alone.
Flattening Deeper Arrays
If your arrays are nested more than one level, pass a depth:
const numbers = [1, [2, [3, [4]]]]numbers.flat() // [1, 2, [3, [4]]]numbers.flat(2) // [1, 2, 3, [4]]numbers.flat(Infinity) // [1, 2, 3, 4]
Infinity keeps going until there's nothing left to flatten, which is handy
when you don't know how deep the data goes.
Using flatMap()
A common pattern is calling map and
then flattening the result. flatMap does both in one step:
const posts = [{ title: "Map", tags: ["js", "arrays"] },{ title: "Grid", tags: ["css"] },]const allTags = posts.flatMap((post) => post.tags)// ["js", "arrays", "css"]
Note that flatMap only flattens one level.
Browser Support
flat and flatMap are part of ES2019 and work in the latest Chrome, Firefox
and Safari. They don't work in Internet Explorer or the current version of Edge,
so if you need to support those you'll want a polyfill or a fallback.
For one level, the
spread operator with concat
does the same thing (Babel will compile the spread for Internet Explorer):
const flat = [].concat(...tags)// ["js", "react", "css", "html", "a11y"]
And for any depth, a small recursive function with reduce does the trick:
const flattenDeep = (array) =>array.reduce((result, item) =>result.concat(Array.isArray(item) ? flattenDeep(item) : item),[])flattenDeep([1, [2, [3, [4]]]]) // [1, 2, 3, 4]
If you're using Babel with a polyfill, you can use flat and flatMap today
and skip the fallbacks.
Have some feedback on this post? .