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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!