The first part the ‘flatMap()’ method that we are going to look at is the ‘map()’ portion. The basis of the ‘map()’ method is to call a function on every element of an array and return a new array populated with the results.
In the example above, we have created an array and a function that multiplies each element in the array by two. When we console log the results of running that array through the map method while passing it the ‘double’ function, we we that we see that the numbers are indeed doubled but also that we get an array with elements of arrays that only have one element each.
As you can see we have called the ‘flat()’ method on our ‘newArray’ and instead of an array where each element is an single element sub array, we have one array containing the same numerical values as prior.
This is fine and works well enough but in the interest of finding more efficient solutions, no matter how minimal that increase may be there is a way to do this in a slightly more effective manner. By using the ‘flatMap()’ method, we are able to combine the ‘map()’ and ‘flat()’ methods into one.
Here we have just taken the same example as shown above but instead of calling the ‘map()’ and ‘flat()’ methods separately, we have simply called the ‘flatMap()’ on our ‘array’ element. As we can see, have the same results logged to the console as we did while calling the two methods individually but here we have done it as a single method instead of two separate instances making our code and computing a bit more efficient.