1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

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

    Mike SherovMike Sherov
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

    Man: 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.

    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.

    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.

    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.

    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.