24
Array FlatMap
FlatMap is a single method which can be usable for flat and map methods.
As you know flat()
, flattening the 1-level deep and map()
to loop into an array.
If we include both, we called flatMap()
๐
So, instead if calling two methods flat()
and map()
, you can use single method called flatMap()
.
let plants = ['๐', '๐ฒ', '๐ป', '๐น'];
// โ map + flat
plants.map(plant => [plant, '๐']).flat();
// Output
//["๐", "๐", "๐ฒ", "๐", "๐ป", "๐", "๐น", "๐"]
// โ
flatMap
plants.flatMap(plant => [plant, "๐"])
// Output
// ["๐", "๐", "๐ฒ", "๐", "๐ป", "๐", "๐น", "๐"]
๐ FlatMap() always do first map() and then it flat().
In flat()
, we use to pass arguments where you set the depth, arguments define how deep a nested array should be flattened.
let plants = [[["๐ป", "๐น"]]];
plants.flat(2);
// ["๐ป", "๐น"]
let plants = [[["๐ป", "๐น"]]];
plants.flatMap(plant => [plant]);
// [["๐ป", "๐น"]]
Yes, You can also do filter here using flatMap()
.
let arr = [5, 4, -3, 20, -4, 18]
arr.flatMap(i => {
return i < 0 ? [] : [i];
})
// [5, 4, 20, 18]
flatMap()
method always helps if you want to use map and flat methods both together.
Thanks for reading the article โค๏ธ
๐ Twitter | ๐ฉ๐ปโ๐ป suprabha.me | ๐ Instagram |
24