Use ES2019 Array.prototype.flat to Flatten Multidimensional Arrays

Mike Sherov
InstructorMike Sherov
Share this video with your friends

Social Share Links

Send Tweet
Published 6 years ago
Updated 4 years ago

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.

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

[00:07] 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.

[00:34] 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.

[00:54] 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.

[01:09] 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.