Flat and FlatMap in Arrays - Let's Learn ECMAScript 2021 with Earl Duque
For this lesson, a few more array
utilities that are available to you. The two I'm talking about today, flat
and flatMap came out in ECMAScript 2019,
so a little bit more newer, very simple utilities
but comes up in different contexts. A lot of these are about quality of life
for those very specific scenarios. and this one has a very specific scenario. So let me show you. So let's say I have an array and this array has
a bunch of numbers in it. Okay, I think that's enough. But instead of it
just being flat like this, I am going to go wild and add a bunch of groupings around it. So now it's nested arrays within nested arrays within nested arrays. If I wanted to flatten them, I just have to say myArray.flat
and I'll go ahead and print that, I’ll JSON.stringify it so that we can see
really what's going on in the background. And you
can see that I actually only got rid of one of the levels of nested arrays. And that's because if you don't
give it a parameter here, it defaults into flattening it
by one level only. And so if I put in two here, you'll see that
another level was destroyed. And then if I put three here ago,
it goes completely flat because I had only three levels
of nested arrays in there. So you can even be a little bit
more granular in how far down you want to deepen
this nested array of arrays. And lastly, I want to show you flatMap, which is similar to map, but after it does its mapping functionality, it
then flattens it afterwards. So it's a very efficient way for you
to do your mapping operations, followed by a flattening, especially when
you're dealing with arrays of objects. So here you can see
I have an array of objects. So this array has two objects in it,
both with ID and notes in it. and my flatMap is an arrow function. So for every incident
inside of that array, and it's going to create a note of it,
And then after that, it flattens them all down into one single
array level. And so before I run this, notice
that the notes on the first incident
is an array of multiple items so this is actually multiple
levels of nested arrays. but because I'm saying flatMap instead of just map, when I run the script,
it flattens down into one single level. Such little things. But you'll never know when you are needing
these the most, and especially when you copy and paste it from like StackOverflow
or from someone else's explanation. It's good to be able to use
all the different functionality of JavaScript instead of worrying about
if it's compatible to ES5 or not. Cool.
https://www.youtube.com/watch?v=7hfO5ILv4_U