How to flatten an array in JavaScript

By

Learn how to flatten a JavaScript array with flat() and flatMap(), including using flat(Infinity) to fully flatten nested arrays.

~~~

ES2019 introduced two methods to the Array prototype: flat and flatMap. They are both very useful to what we want to do: flatten an array.

They were new when I first wrote this post, and only the latest browsers supported them. Today there’s nothing to worry about: every browser has shipped them since January 2020, and Node.js has had them since version 11. MDN lists them as Baseline, widely available.

Let’s see how they work.

flat() is an array instance method that can create a one-dimensional array from a multidimensional array.

Example:

['Dog', ['Sheep', 'Wolf']].flat()
//[ 'Dog', 'Sheep', 'Wolf' ]

By default it only “flats” up to one level.

You can add a parameter to flat() to set the number of levels you want to flat the array to.

Set it to Infinity to have unlimited levels:

['Dog', ['Sheep', ['Wolf']]].flat()
//[ 'Dog', 'Sheep', [ 'Wolf' ] ]

['Dog', ['Sheep', ['Wolf']]].flat(2)
//[ 'Dog', 'Sheep', 'Wolf' ]

['Dog', ['Sheep', ['Wolf']]].flat(Infinity)
//[ 'Dog', 'Sheep', 'Wolf' ]

If you are familiar with the JavaScript map() method of an array, you know that using it you can execute a function on every element of an array.

If not, check my JavaScript map() tutorial.

flatMap() is an Array prototype method that combines flat() with map(). It’s useful when calling a function that returns an array in the map() callback, but you want your resulted array to be flat:

['My dog', 'is awesome'].map(words => words.split(' '))
//[ [ 'My', 'dog' ], [ 'is', 'awesome' ] ]

['My dog', 'is awesome'].flatMap(words => words.split(' '))
//[ 'My', 'dog', 'is', 'awesome' ]

Older codebases

For new code the native methods are all you need. If you maintain an old project that must still run in a browser without flat(), you can use Babel to compile your code to a previous ES version, or use the flatten(), flattenDeep() and flattenDepth() functions provided by Lodash.

The cool thing about Lodash is that you don’t need to import the whole library. You can use those functions individually using those packages:

Here’s how to flatten an array using lodash.flatten:

import flatten from 'lodash.flatten'

const animals = ['Dog', ['Sheep', 'Wolf']]

flatten(animals)
//['Dog', 'Sheep', 'Wolf']

Want me to talk about your product? You can sponsor this site.

~~~

Related posts about js: