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(),…


This content originally appeared on DEV Community and was authored by Suprabha

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


This content originally appeared on DEV Community and was authored by Suprabha


Print Share Comment Cite Upload Translate Updates
APA

Suprabha | Sciencx (2021-07-24T20:12:52+00:00) Array FlatMap. Retrieved from https://www.scien.cx/2021/07/24/array-flatmap/

MLA
" » Array FlatMap." Suprabha | Sciencx - Saturday July 24, 2021, https://www.scien.cx/2021/07/24/array-flatmap/
HARVARD
Suprabha | Sciencx Saturday July 24, 2021 » Array FlatMap., viewed ,<https://www.scien.cx/2021/07/24/array-flatmap/>
VANCOUVER
Suprabha | Sciencx - » Array FlatMap. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/07/24/array-flatmap/
CHICAGO
" » Array FlatMap." Suprabha | Sciencx - Accessed . https://www.scien.cx/2021/07/24/array-flatmap/
IEEE
" » Array FlatMap." Suprabha | Sciencx [Online]. Available: https://www.scien.cx/2021/07/24/array-flatmap/. [Accessed: ]
rf:citation
» Array FlatMap | Suprabha | Sciencx | https://www.scien.cx/2021/07/24/array-flatmap/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.