Demystifying Array.prototype.flat
Laurie
Posted on June 18, 2019
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]]
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()
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)
In Summary
It's a miracle!!! Go forth and enjoy the awesomeness that ES2019 has gifted us.
Posted on June 18, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.