Become a member
to unlock all features

Level Up!

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


    Use ES2019 Array.prototype.flat to Flatten Multidimensional Arrays


    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.



    Become a Member to view code

    You must be a Pro 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
    orLog In




    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.