## DEV Community is a community of 700,720 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

loading...

# Array FlatMap

Suprabha
π₯ New JS, CSS, HTML articles every week π₯ Frontend engineer @gojekindonesia π©π»βπ» http://instagram.com/suprabhasupi
γ»1 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]
``````

## Summary β

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

Thanks for reading the article β€οΈ

 π Twitter π©π»βπ» suprabha.me π Instagram

Aya Bouchiha

Thank you!