Tutorial

Flatten Arrays in Vanilla JavaScript with flat() and flatMap()

Published on September 28, 2018
author

Alligator.io

Flatten Arrays in Vanilla JavaScript with flat() and flatMap()

Libraries like Lodash and Underscore.js have provided us with utilities to help with flattening arrays for a while now. Thanks to the continuous evolvement of the ECMAScript standard, weโ€™ll now be getting methods to do that directly in vanilla JavaScript, without the need for external utility functions.

As you may have seen if youโ€™ve been following the interwebs lately, these new methods to flatten arrays have triggered quite a bit of a stir. Now known at the #Smooshgate, the gist of it is that Array.prototype.flatten() is being monkey-patched by MooTools, which is still used by some websites, so at some point a suggestion popped-up to name the method smoosh instead of flatten as a joke, to avoid breaking some websites still relying on MooTools. A lot of people took the smoosh suggestion seriously, and quite a bit of keystrokes were lost over this.

Now that the dust has settled from this mini-controversy, the final decision has been to go with flat and flatMap as the two method names to help with flattening arrays in JavaScript.

Letโ€™s go over them now.

Array.prototype.flat()

As its name suggests, the flat() method available on the Array prototype returns a new array thatโ€™s a flattened version of the array it was called on. Without arguments passed-in, a depth of 1 is assumed. Otherwise, if a number is passed-in as the first argument, itโ€™s used as the maximum depth to flatten the array.

Hereโ€™s a simple example:

const animals = [['🐕', '🐶'], ['😺', '🐈']];

const flatAnimals = animals.flat();
// same as: const flatAnimals = animals.flat(1);

console.log(flatAnimals);

// ['🐕', '🐶', '😺', '🐈']

And notice what happens when the total depth of the array is larger than the maximum depth for the flat method:

const animals = [['🐕', '🐶'], ['😺', '🐈', ['😿',['🦁'], '😻']]];

const flatAnimals = animals.flat(2);

console.log(flatAnimals);
// ['🐕', '🐶', '😺', '🐈', '😿',['🦁'], '😻']

You can use Infinity if you want to flatten an array of arbitrary depth:

const animals = [['🐕', '🐶'], ['😺', '🐈', ['😿',['🦁'], '😻']]];

const flatAnimals = animals.flat(Infinity);

console.log(flatAnimals);
// ['🐕', '🐶', '😺', '🐈', '😿', '🦁', '😻']

Array.prototype.flatMap()

The flatMap() method available on the Array prototype has the same effect as using the map() method followed by the flat() method with the default depth of 1. In other words, flatMap() maps each value to a new value and then the resulting array is flatten up to a maximum depth of 1.

Hereโ€™s an example:

const animals = ['🐕', '🐈', '🐑', '🐮'];
const noises = ['woof', 'meow', 'baa', 'mooo'];

const mappedOnly = animals.map((animal, index) => [animal, noises[index]]);
const mappedAndFlatten = animals.flatMap((animal, index) => [animal, noises[index]]);

console.log(mappedOnly);
// [['🐕', 'woof'], ['🐈', 'meow'], ['🐑', 'baa'], ['🐮', 'mooo']

console.log(mappedAndFlatten);
// ['🐕', 'woof', '🐈', 'meow', '🐑', 'baa', '🐮', 'mooo']

The callback function passed-into flatMap() expects the same arguments as the ones that can be passed-in to the traditional map() method, the first being the current value, the second being the index of the current value in the array and the third being the full array being mapped over.

Browser Support

Support is already pretty good, with the latest version of most recent browsers supporting both methods. For example, the methods are supported in Chrome 69+, Firefox 62+ and Safari 12+. There currently is no support for any version of Internet Explorer or Edge, at the time of this writing.

If you want to start using it now and support all browsers, you can always use the official polyfill/shim for flat and flatMap.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Alligator.io

author

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the โ€œreport an issueโ€œ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
ย 
Leave a comment
๏ปฟ

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow โ€” whether you're running one virtual machine or ten thousand.

Learn more