DEV Community

Cover image for Javascript's reduce method in a nutshell.
Amine Amhoume
Amine Amhoume

Posted on

Javascript's reduce method in a nutshell.

The word "reduce" in the English language means :

to diminish in size, amount, extent, or number

Let's suppose that we have an array of items

const cartItems = [1,3,5,7,9];

I want the sum of all the items.

I could use the For Loop but it's going to be a bit hairy. The method reduce() will give us one total number with less code (always go for the less-code option).

reduce() takes two arguments: a callback function (the reducer itself) and an initial value. The callback function takes two arguments: the previous value and the current value:

let total = cartItems.reduce((previousValue, currentValue) => {
    return previousValue + currentValue;
}, 0)
Enter fullscreen mode Exit fullscreen mode

Let's calculate the first rotation on the array.

The previousValue is going to be equal to 0 while the currentValue is going to be equal to the first item in the array, which is 1.

Next, the previousValue is going to be equal to 1 while the currentValue is going to be equal to 3 and so it goes. The total amount will be sum of all the numbers: 25

Keep in mind that the initial Value is totally optional. When omitted, the first value of the array is used as an initial value.

Note: the reverse of the reduce() method is reduceRight(). Yes! It takes items from right to left.

Ladies and gentlemen, that was a quick tutorial of the reduce() method.

Don't forget to practice.

Thank you.

Discussion (8)

Collapse
basharath profile image
Basharath

It's a good article. You should avoid saying previous value, because it doesn't actually hold the previous value.

previousValue accumulates all the results, nothing but the squeezing of the array is stored in that. So it is a convention to call it an accumulator or store.

General convention
arr.reduce((acc, curr) => {}, initial)👍

Collapse
amiinequ profile image
Amine Amhoume Author

I appreciate that. You are definitely right! But, the thing I try to write articles for people with low level English and not to confuse them with puzzling words. Thank you again.

Collapse
mfurmaniuk profile image
Michael

As a native speaker I found the previous and current more confusing to be honest. Very nice that you can do this sort of thing in JS but I did have to reread your example a couple of times as it didn't sound right to me.

Thread Thread
amiinequ profile image
Amine Amhoume Author

Thank you Michael. Feedback like yours is what keeps me improving. I will take that in consideration when writing my next article which I will publish in a few days.

Collapse
thepeoplesbourgeois profile image
Josh • Edited on

Anything for can do, reduce can do cleaner (i.e., with fewer side effects).

Getting certain items in an array:

[1, 'pears', new Set()].reduce(
  (iters, maybeIterable) => {
    if (maybeIterable[Symbol.iterator]) {
      iters.push(maybeIterable)
    }
    return iters;
  }, 
  []
);
// => [ 'pears', Set [] ]
Enter fullscreen mode Exit fullscreen mode

Transforming the contents of the array, in-place:

const words = "why would you want me to spell these words backwards".split(" ");
 words.reduce(
  (backwords, word, index) => {
    backwords[index] = word.split("").reverse().join("");
    return backwords;
  }, 
  words
)

console.log(words.join(" "))
// => yhw dluow uoy tnaw em ot lleps eseht sdrow sdrawkcab
Enter fullscreen mode Exit fullscreen mode

Summing a bunch of numbers:

// see post example
Enter fullscreen mode Exit fullscreen mode

Even mimicking forEach(), if you hate optimized native code:

['butter', 'milk', 'eggs', 'whatever'].reduce(
  (_, item) => console.log(item),
  null // if no accumulator is passed, the first item in the list won't be logged
)

/*
butter
milk
eggs
whatever

=> undefined
*/
Enter fullscreen mode Exit fullscreen mode
Collapse
amiinequ profile image
Amine Amhoume Author

Excellent examples man! reduce() is truly powerful.

Collapse
jonrandy profile image
Jon Randy

You didn't mention that the initial value is actually optional. If you omit it, the first value of the array is used, and the reduce proceeds from the next value

Collapse
amiinequ profile image
Amine Amhoume Author

Thanks for the reminder Jon. I had that in mind but didn't bother to put it but now I think I should.