Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
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

    Use ES2019 Array.prototype.flat to Flatten Multidimensional Arrays

    Mike SherovMike Sherov
    javascriptJavaScript

    ES2019 introduces the Array.prototype.flat method. In this lesson, we'll flatten a multidimensional array using Array.prototype.reduce and Array.prototype.concat, and then refactor the code to do the same thing using the .flat method. We'll then use the depth parameter to flatten a 3 dimensional array.

    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
    Transcript

    Transcript

    Instructor: Here we have a two-dimensional array of scores, with each element of the outer array being an array itself.

    Here we have a function called Average, which takes an array and produces the arithmetic average of the values passed to it. If we wanted to find the average of our scores before ES2019, we need to take our scores and reduce them, iterating through each score and concatenating it to a flat list of scores. If we then log the average, we see that the answer is 96.

    ES2019 introduces the flat method on the array prototype which performs the same functionality. If we console log again, we see that it also produces 96. That is to say, the flat method on the array prototype will concatenate subarrays of a multidimensional array.

    By default, flat will only concatenate one level deep. If we output scoresByDay.flat with a three-level deep array, we see that it still produces a multidimensional array.

    Flat takes in a parameter that can specify how deep you want the flattening to go. If we specify 2, we now see it flattens the entire array.

    Discuss

    Discuss