How to use flatMap to map and flatten an array in one function. Use flatMap to add items too!
Become an expert. One newsletter at a time.
Hey everyone, It’s Bill Walker providing you with another gem of information - this time using flatMap with a list/array for JavaScript and Typescript.
Why use flatMap? It is the equivalent of using flat and map in one function.
We will take this one step further and demonstrate how to use flat map to insert items into an array.
We start with an array, capitalCities which contains:
We can apply flatMap to the array and see that it will reduce the depth by 1 and map to a new variable, capitalCityList.
The result is as expected, the array depth is reduced by 1 level.
We can also insert a new city, unicornutopia, the capital city of Unicornia, into the capitalCities array. We use Array.isArray to find an array within the capitalCities array and create return the array, city, and unicornutopia after it.
At this point you might have noticed that because we returned an array when we found an array that it did not reduce the array depth.
We will do a little demo using flat within flatMap so that we can add a new city and reduce the depth! To do this we will add Kelpie City to our Capital Cities list.
The results are:
We can see above that the array containing European city has been flattened. However, we still have the array with UK capital cities within it. We can reduce the array of capitalCities to a depth of one and add a city!
The output in the console shows it works perfectly as we have all the cities in an array with a depth of 1.
In the next newsletter we will demonstrate how to remove items from an array while using flatMap.
Please subscribe and share!