An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
July 24, 2021 08:12 pm GMT
Original Link: https://dev.to/suprabhasupi/array-flatmap-4cn7
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 + flatplants.map(plant => [plant, '']).flat();// Output//["", "", "", "", "", "", "", ""]// flatMapplants.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
Original Link: https://dev.to/suprabhasupi/array-flatmap-4cn7
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To