Use JavaScript ES2019 flatMap to Map and Filter an Array

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 filtering an array in a single iteration. 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.

Stephen James
~ 5 years ago

Seem like chaining filter then flatmap would be clearer? const counts = this.records.filter(record => this.id === record.id).flatMap(record => [record.am, record.pm]); IMO this is more explicit that you are filtering rather than the ternary

Mike Sherovinstructor
~ 5 years ago

Hi Stephen,

Thanks for the feedback. You can certainly do that! To me, it's all about whatever is clearest for you and your team. In this case, I personally prefer the ternary, and in the case when working with large arrays, I'd prefer to do one iteration via flatMap rather than 2 iterations via filter and flatMap.

Elliott Grieco
~ 5 years ago

reduce is what I used to perform algorithms like this before but flatMap is a great alternative!

J. Matthew
~ 5 years ago

See my comments on the previous video, haha—they all apply here as well (except that the counts declaration in the transcript has been fixed). I watched through these videos once already, so this one must have been in the back of my mind.