.flat()
Method
As its name states, the flat method flattens a nested array to the level we state. The default flattening level is 1, i.e., it flattens a nested array to 1 level (like differentiation - kinda):
Let’s take an example.
In this arr
, the nest is only 1 level deep, so the default .flat()
works:
On the other hand, something like the following array will require more than 1 level of flattening, since the nest is deeper than just 1 level:
For going deeper than 1 level, all we need to do is add the number of levels we want to go within the nested array in the flat bracket:
Like doing: (kinda?)
Practical Example
Let’s consider the following data.
Let’s say that we want to calculate the overall balance of all these people by adding all their account activities. We can do that like this:
Note:
acc
here is just a variable inside the bracket to carry out the function. It could be named anything else. I used it to be understood as ‘an individual account of accounts’. Same foraccumulator
andelement
.
.flatMap()
Method
But what if there’s a shorter way than using .flat()
sometimes? Yup, that is the flatMap method.
.flatMap()
, like its name suggests, combines .flat()
and .map()
methods into one. Neat.
So, going back to the practical example from above, we could shorten it like this:
Caveat
The
.flatMap()
method can only go 1 level deep to flatten an array. So, if we want to use chaining that includes mapping and flattening for a deeply nested array, we cannot use the.flatMap()
method and will have to stick to doing.map(le some kind of transformation).flat(number-of-levels)
.