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.
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
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
.
reduce
is what I used to perform algorithms like this before but flatMap
is a great alternative!
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.