DEV Community

Cover image for Array FlatMap
Suprabha
Suprabha

Posted on

15 4

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
// ["πŸ’", "🍁", "🌲", "🍁", "🌻", "🍁", "🌹", "🍁"]
Enter fullscreen mode Exit fullscreen mode

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);

// ["🌻", "🌹"]
Enter fullscreen mode Exit fullscreen mode

flatMap() do only 1 level deep flattening.

let plants = [[["🌻", "🌹"]]];
plants.flatMap(plant => [plant]);

// [["🌻", "🌹"]]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

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

Top comments (1)

Collapse
 
ayabouchiha profile image
Aya Bouchiha β€’

Thank you!

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay