Blog

Demystifying Array.prototype.flat

ES2019 is officially available for us all to play with. Caution ahead, make sure that if you use these features your browser and/or transpiler supports them.

Without further ado, let’s dive into our first new feature. I give you Array.prototype.flat!

The Old Way

Embedded arrays exist in our code for any number of reasons, and to be honest, they’re kind of a pain.

let arr = [1, 2, [3, 4, [5, 6]]]

Handling stuff like this used to require unintuitive trickery like the code below.

var merged = [].concat.apply([], arr);

And that would only result in one level of depth being flattened!

[1, 2, 3, 4, [5, 6]]

Boooooooo

The New Way!

Then along came flat(). And this is a game changer.

Doing the same thing we did above is a breeze.

var merged = arr.flat(1)

That argument is just the depth that we want to flatten. So one level deep gets us this, just like before.

[1, 2, 3, 4, [5, 6]]

Magic

But what is so incredibly powerful is that it doesn’t stop there. We can flatten our entire array in a single line.

var merged = arr.flat(2)

Becomes

[1, 2, 3, 4, 5, 6]

Wait for It

We’ve even been gifted one more awesome feature. Let’s say we don’t know the depth of our array but we want to flatten it all the way.

var merged = arr.flat(Infinity)

Ron Swanson saying what the hell just happened

In Summary

It’s a miracle!!! Go forth and enjoy the awesomeness that ES2019 has gifted us.

Categories: Blog

Tags: , ,

Laurie Barth
18 Jun, 2019