Map and Flatten Multidimensional Arrays with ES2019 Array.prototype.flatMap

Mike Sherov
InstructorMike Sherov
Share this video with your friends

Social Share Links

Send Tweet

ES2019 introduces the Array.prototype.flatMap method. In this lesson, we'll map and flatten a multidimensional array using Array.prototype.map, Array.prototype.reduce and Array.prototype.concat, and then refactor the code to do the same thing using the .flatMap method. Then, we'll see how we can use empty arrays in our map function to act as a filter before mapping.

Man: [00:00] Here we have an array of values that we'd like to flatten. Here is a flatten function that we would use prior to ES2019. Here we have console logged the values.flat and cloned the flat function on values to see what it produces.

[00:15] When we run this code, we see that flat will concatenate all the values together, which includes skipping empty arrays and flattening other arrays. Besides for flat, ES2019 introduces a flatMap function on the array prototype as well. What this does is allows you to provide a map function that will get called before the array concatenation gets called.

[00:40] If I change over to flatMap and use the identity function, which takes a value in and returns that same value, I could see that it's the same as flat. If instead do some more interesting transformation like casting it to a string, we see that it does the mapping function before concatenating. Now that we've seen the most basic functionality to flatMap, let's see what else we can do with it. Here we have a list of counts, with each count being an object of the number of, let's say, birds observed in the AM and PM at different sites.

[01:19] An interesting property of flatMap is that can be used to filter, map, or both on an array. If we do counts.flatMap and iterate over each count, and decide we want to filter out values from site A, we can return if (count.site = A) an empty array, otherwise return the count itself. Now because flatMap will concatenate the resulting values, an empty array basically says ignore this value. If we console log this, we'll see that only the values from site B are returned.

[01:54] Not only can we filter, because this is flatMap, we can return multiple values from our counts and each will be added the resulting array. If we run this again, we'll see that it now returns 2, 4, 1 and 7, which is the AM, the PM value, and the AM and the PM value from site B. Of course, if we only want to map, we could do that too. See? No more filter.