DEV Community

Cover image for JavaScript reduce() method
Chris Bongers
Chris Bongers

Posted on • Updated on • Originally published at daily-dev-tips.com

JavaScript reduce() method

We are checking out some useful array methods, and today we are looking at the reduce() method.

The reduce method can be used to convert our array to one specific single value.

Also, check out my article on the JavaScript filter() method

Using the Javascript reduce() method

The reduce can be used for instance to just count a total, let's say we have the following array.

const items = [
  { name: 'T-shirt plain', price: 9 },
  { name: 'T-shirt print', price: 20 },
  { name: 'Jeans', price: 30 },
  { name: 'Cap', price: 5 }
];
Enter fullscreen mode Exit fullscreen mode

How can we now simply get a total of all these items?

const reduced = items.reduce((total, item) => {
  total += item.price;
  return total;
}, 0);

// 64
Enter fullscreen mode Exit fullscreen mode

What we are doing here is giving the argument total, which is the initialValue, the next argument is the currentValue then we add the price to our total value.

Then at the end, you see a 0 defined, this is the initialValue default.

The arguments for the reduce is as follows:

const new = original.reduce(function(total, current, index, array), initialValue);
Enter fullscreen mode Exit fullscreen mode

Where the following applies:

  • total: Required, the initial value
  • current: Required, the value of the current index
  • index: Optional, array index of the current row
  • array: Optional, array current row belongs to.
  • initialValue: Optional, value to be defined as a starting point.

You can ofcourse also only count certain items, let's say we have discounted items and only want to count those:

const items = [
  { name: 'T-shirt plain', price: 9, discount: true },
  { name: 'T-shirt print', price: 20, discount: false },
  { name: 'Jeans', price: 30, discount: true },
  { name: 'Cap', price: 5, discount: false }
];

const reduced = items.reduce((total, item) => {
  if(item.discount)
    total += item.price;
  return total;
}, 0);

// 39
Enter fullscreen mode Exit fullscreen mode

As you can see, very powerful, but easy to implement method. Really cuts down on a lot of loop logic.

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (4)

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