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
FlatMap is a mix of two words which are derived from latin words blah blah blah...
Array.flatMap is a mixture of two array methods
Array.flatis used for flattening nested arrays. For example
Array.mapis used for creating a new array by performing operations on each array element and returning a value. For example
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:
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:
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:
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!!