DEV Community

Discussion on: JavaScript reduce() method

Collapse
 
lexlohr profile image
Alex Lohr
Array.prototype.reduce((state, item) => newState, initialState)
Enter fullscreen mode Exit fullscreen mode

This one is more powerful than one usually expects, because state needs not be the same type as the item. You can easily replace .filter/.map with .replace (which means that you only need one iteration of the array):

items
  .filter((item) => item.startsWith('a'))
  .map((item) => item.toLowerCase())

items.reduce((items, item) => item.startsWith('a')
  ? [...items, item.toLowerCase]
  : items,
[])
Enter fullscreen mode Exit fullscreen mode

Or you can fill an object instead, for example to count the characters in a string:

string
  .split('')
  .reduce((chars, c) => ({ ...chars, [c]: (chars[c] || 0) + 1 }), {})
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dailydevtips1 profile image
Chris Bongers

Oh wow, actually wasn't aware of that, thanks for bringing that to the attention!
So when you say it's 1 iteration, does that mean even underwater it doesn't loop?

Just wondering from a user performance part of the view, if the reduce is quicker than the filter.map combi?

I would suspect so.

Collapse
 
lexlohr profile image
Alex Lohr

I don't really get that "underwater" question. It is only iterating over the array once, whereas the filter/map variant will iterate once to create a filtered representation of the array and once more to map it.

And yes, the reduce will be somewhat faster, even though the native array methods are pretty optimized already.

Thread Thread
 
dailydevtips1 profile image
Chris Bongers

That was my question indeed if it actually is only 1 iteration.
Very cool stuff actually