Usage of FlatMap in JavaScript?

PaperInFlames
2 min readDec 13, 2023

--

If you’ve already searched for its definition, you’d have learned that Flatmap will first map the elements and then flatten them.

If you didn’t understand it clearly, this article will help you for sure.

Scenario:

Just imagine, you’re working in a book publishing company and you have a list of authors in the form of the below array.

Requirement:

You want to mail the list of best-selling books to the advertising team for the New Year flash Sale, which should be an array of book names.

Approach 1:

By filtering the list of authors based on the bestSellingAuthor flag and get the list of those authors.

Output for Approach 1:

Here, best-selling books are nested inside the array, which is not expected. Let's see the next approach.

Approach 2:

By using Spread operator on filtered values.

Output for Approach 2:

Approach 3:

By using FlatMap operator on filtered values.

Output for Approach 3:

Here instead of pushing the values with the help of the spread operator, I’ve directly returned the values of the flatMap operator, which does the same.

Hope this helps 😀🫠

--

--