Demystifying Array.prototype.flat

laurieontech

Laurie

Posted on June 18, 2019

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]]]
Enter fullscreen mode Exit fullscreen mode

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

var merged = [].concat.apply([], arr);
Enter fullscreen mode Exit fullscreen mode

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

[1, 2, 3, 4, [5, 6]]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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]]
Enter fullscreen mode Exit fullscreen mode

Note that if you don't pass an argument it defaults to 1. That means these statements are equivalent.

arr.flat(1)
//is the same as
arr.flat()
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Becomes

[1, 2, 3, 4, 5, 6]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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.

💖 💪 🙅 🚩
laurieontech
Laurie

Posted on June 18, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Introducing Object.fromEntries
javascript Introducing Object.fromEntries

July 2, 2019

Understanding Array.prototype.flatMap
javascript Understanding Array.prototype.flatMap

June 25, 2019

Demystifying Array.prototype.flat
javascript Demystifying Array.prototype.flat

June 18, 2019