DEV Community

Discussion on: Javascript reduce 101

Collapse
 
mbackermann profile image
Mauricio Ackermann

It doesn't make any sense to use reduce to reduce it to an array. We could use filter only to do the same:

wealthiestPeople.filter(function(p){
  return p.worth < 100000000000
})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
iggredible profile image
Igor Irianto

Yup! Totally makes sense. I agree that using reduce here is overkill.

However, my goal is to show two things:

  1. How to understand how accumulator and current value change each iteration
  2. That reduce can return either: an array, an object, or a primitive value.

I can probably think of another case where reduce is more useful than map/filter, but I'll have to change the example. I think it's easier to grasp of I use one array example throughout the whole article. It was a huge revelation when I first learned that reduce can return array or object and I hope to convey the same to readers :)

Really appreciate the feedback!

For those who read this, filter is the better tool for this situation. But the point stands that reduce can give the same result, just more work is required.

Collapse
 
kvsm profile image
Kevin Smith ๐Ÿด๓ ง๓ ข๓ ณ๓ ฃ๓ ด๓ ฟ

A good example would be a reduce which does both a map and a filter - if you did the same with map, then filter, you'd have to iterate over the array twice.

Thread Thread
 
iggredible profile image
Igor Irianto

I updated the post to include a basic map/ filter case. Thank you so much for the suggestion!

I hope it conveys the point :)

Collapse
 
mbackermann profile image
Mauricio Ackermann

I get what you mean! I think itโ€™s important to make it clear thatโ€™s not the best solution since in this case reduce will be more memory consuming. Keep the good work!

Thread Thread
 
iggredible profile image
Igor Irianto

I updated the post so it now includes your filter example ๐Ÿ‘