50

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

 5 years ago
source link: https://www.tuicool.com/articles/hit/VbAziiE
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

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 = [[':dog2:', ':dog:'], [':smiley_cat:', ':cat2:']];

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

console.log(flatAnimals);

// [':dog2:', ':dog:', ':smiley_cat:', ':cat2:']

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

const animals = [[':dog2:', ':dog:'], [':smiley_cat:', ':cat2:', [':crying_cat_face:',['  '], ':heart_eyes_cat:']]];

const flatAnimals = animals.flat(2);

console.log(flatAnimals);
// [':dog2:', ':dog:', ':smiley_cat:', ':cat2:', ':crying_cat_face:',['  '], ':heart_eyes_cat:']

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

const animals = [[':dog2:', ':dog:'], [':smiley_cat:', ':cat2:', [':crying_cat_face:',['  '], ':heart_eyes_cat:']]];

const flatAnimals = animals.flat(Infinity);

console.log(flatAnimals);
// [':dog2:', ':dog:', ':smiley_cat:', ':cat2:', ':crying_cat_face:', '  ', ':heart_eyes_cat:']

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 = [':dog2:', ':cat2:', ':sheep:', ':cow:'];
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);
// [[':dog2:', 'woof'], [':cat2:', 'meow'], [':sheep:', 'baa'], [':cow:', 'mooo']

console.log(mappedAndFlatten);
// [':dog2:', 'woof', ':cat2:', 'meow', ':sheep:', 'baa', ':cow:', '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 .


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK