What is flatMap in JavaScript? And how made my code cleaner
Tags: javascript, programming, webdev, codenewbie
Published: 2021-09-18 08:32:27

Have you ever looked at a JavaScript in built function and said to yourself: 
> I understand what this is but I do not know where I can use this.

Well, this exact thought came to mind when I read about `Array.flatMap()`. So I started looking for its applications in my day-to-day coding and viola!! I found a use case. In this post, we will first see what `Array.flatmap()` is and then look at how I used it in a real problem. 

## What exactly is `Array.flatMap`?

> FlatMap is a mix of two words which are derived from latin words blah blah blah...

Just kidding.

`Array.flatMap` is a mixture of two array methods `Array.flat` and `Array.map`. Individually,

- `Array.flat` is used for flattening nested arrays. For example

```jsx
const names = ['Amit', 'Karishma', 'Kunal', ['Pankaj', 'Rahee']];

console.log(names.flat());
// expected output: ["Amit", "Karishma", "Kunal", "Pankaj", "Rahee"]
```

- `Array.map` is used for creating a new array by performing operations on each array element and returning a value. For example

```jsx
const names = ['Amit', 'Karishma', 'Kunal', 'Pankaj', 'Rahee'];
const everyOneLovesDogs = names.map((name) => {
  return `${name} loves dogs`;
});

console.log(everyOneLovesDogs);
// expected output: ["Amit loves dogs", "Karishma loves dogs", "Kunal loves dogs", "Pankaj loves dogs", "Rahee loves dogs"]
```

So as you can guess, `Array.flatMap` maps an array and then flattens the nested arrays in the returned array. A quick example of flatMap looks like this:

```jsx
const usersWithInterests = [
  {
    name: 'Amit',
    interests: ['Cricket', 'Music'],
  },
  {
    name: 'Karishma',
    interests: ['Drawing', 'Reading'],
  },
  {
    name: 'Pranav',
    interests: ['Crafting', 'Biking'],
  }
];

const interests = usersWithInterests.flatMap((user) => {
  return user.interests;
});

console.log(interests);
// Expected Output: ["Cricket", "Music", "Drawing", "Reading", "Crafting", "Biking"]
```

## How I used `Array.flatMap` in a real-world problem?

I was working on a feature where I had to create a dropdown for categories for products. The actual response from `getProducts` API looks like this:

```jsx
const response = {
  "status": "success",
  "products": [
    {
      "name": 'One Plus 7T',
      "categories": ['Technology', 'Mobile', 'SmartPhone'],
      "description": 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      "rating": '4.5'
    },
    {
      "name": 'MacBook Pro 2018',
      "categories": ['Technology', 'Computer', 'Laptop'],
      "description": 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      "rating": '4.8'
    },
    {
      "name": 'LG Monitor 221G',
      "categories": ['Technology', 'Monitor'],
      "description": 'Lorem ipsum dolor sit amet, consectetur adipiscing elit.',
      "rating": '4.3'
    }
  ]
}
```

The product object has categories as a key for which the values are stored in the array. 

So I had to do 3 things

- Get the categories from each product
- Flatten that array
- Get unique values from the array.

Instead of using 2 separate functions for first two tasks, i used one function: `Array.flatmap`. And then applied the set operation on that array to get unique values. 

The final code snippet looked something like this:

```jsx
const { products } = response;
const allCategories = products.flatMap((product) => {
  return product.categories;
});

const uniqueCategories = [...new Set(allCategories)];

console.log(uniqueCategories);
// Expected Output: ["Technology", "Mobile", "SmartPhone", "Computer", "Laptop", "Monitor"]
```

Conclusion 

I hope now you folks can also apply `Array.flatMap` in cases where they fit and produce a cleaner code. For more such interesting tidbits, stay tuned in. Until then, Happy Coding!!


*This article was [originally published here](https://www.amitkhonde.com/blog/what-is-flatmap-in-javascript). For more such interesting reads, [visit my blog](https://www.amitkhonde.com/blog).*