/

How to Flatten an Array in JavaScript: A Practical Guide

How to Flatten an Array in JavaScript: A Practical Guide

In JavaScript, flattening an array can be a common task. Fortunately, the ES2019 update introduced two new methods, flat and flatMap, to the Array prototype to simplify this process. However, it’s essential to note that these methods are only supported by more recent versions of browsers such as Firefox 62+, Chrome 69+, Edge 76+, and Safari 12+. If you need to support older browsers, you can consider using Babel to backport your code to a previous ECMAScript version.

If you prefer not to deal with Babel and don’t have a build step already in place, you can opt for the flatten(), flattenDeep(), and flattenDepth() functions offered by Lodash. One advantage of Lodash is that it allows you to use these functions individually by installing the corresponding packages.

To flatten an array using the lodash.flatten package, follow these steps:

1
2
3
4
5
6
const flatten = require('lodash.flatten');

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

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

Alternatively, you can use the native JavaScript methods, flat() and flatMap(), to achieve the same result.

The flat() method is an instance method of arrays that creates a one-dimensional array from a multidimensional array. By default, it only flattens up to one level. However, you can specify the number of levels to which you want to flatten the array by providing a parameter to flat(). To flatten the array to an unlimited number of levels, set the parameter value to Infinity.

Example:

1
2
['Dog', ['Sheep', 'Wolf']].flat();
//[ 'Dog', 'Sheep', 'Wolf' ]
1
2
3
4
5
6
7
8
['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 map() method of an array in JavaScript, you may know that it allows you to execute a function on every element of the array. The flatMap() method combines the functionality of flat() and map(). It is particularly useful when calling a function within the map() callback that returns an array, but you want the final result to be a flat array.

Example:

1
2
3
4
5
['My dog', 'is awesome'].map(words => words.split(' '));
//[ [ 'My', 'dog' ], [ 'is', 'awesome' ] ]

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

Overall, the flat() and flatMap() methods are convenient tools for quickly flattening arrays in JavaScript. Whether you choose to use the native methods or leverage the power of Lodash, these techniques will improve your array manipulation capabilities.

tags: [“JavaScript”, “array manipulation”, “flattening arrays”]