Array FlatMap

Array FlatMap

ยท

2 min read

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
// ["๐Ÿ’", "๐Ÿ", "๐ŸŒฒ", "๐Ÿ", "๐ŸŒป", "๐Ÿ", "๐ŸŒน", "๐Ÿ"]

How flatMap() works?

๐Ÿ“ 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);

// ["๐ŸŒป", "๐ŸŒน"]

flatMap() do only 1 level deep flattening.

let plants = [[["๐ŸŒป", "๐ŸŒน"]]];
plants.flatMap(plant => [plant]);

// [["๐ŸŒป", "๐ŸŒน"]]

Filter using flatMap ๐Ÿ˜‰

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]

Reference ๐Ÿง

Summary โˆ‘

flatMap() method always helps if you want to use map and flat methods both together.

Thanks for reading the article โค๏ธ

Buy Me A Coffee

๐ŸŒŸ Twitter ๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป suprabha.me ๐ŸŒŸ Instagram

Did you find this article valuable?

Support Suprabha Supi by becoming a sponsor. Any amount is appreciated!