Map Elements of an Array with ES2019 flatMap

InstructorMike Sherov

Share this video with your friends

Send Tweet

ES2019 introduces the Array.prototype.flatMap method. In this lesson, we'll investigate a common use case for mapping and flattening a multidimensional array. We'll then see how to do this using Array.prototype.reduce, and then refactor the code to do the same thing using the ES2019 .flatMap method.

Tony Whomever
~ 5 years ago

Great lesson! Quick note - code below is showing: averageCount() { const counts = this.records.forEach(record => { counts.push(record.am, record.pm); }); return average(counts) }, Shouldn't counts be declared as follows?: const counts = [];

Mike Sherovinstructor
~ 5 years ago

Good catch Tony! It'll be fixed shortly. Thanks!

J. Matthew
~ 5 years ago

Looks like the typo @Tony Whomever pointed out is still present in the transcript.

I also noticed that in the video's description it references Array.prototype.reduce, but the actual code uses Array.prototype.forEach.

I like this new method. I've often encountered the problem of wanting to map one array to an array of a different size and being forced either to chain the map to a filter or just write a reduce. Those are both fine solutions, but flatMap looks like it might be more compact and economical, at least under certain conditions.

That being said, I wonder if it will become easy to abuse this method's flexibility and lose the clarity that the filter and reduce syntaxes provide. TBD.