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)
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.
Top comments (9)
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)
👍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.
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.
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.
Anything
for
can do,reduce
can do cleaner (i.e., with fewer side effects).Getting certain items in an array:
Transforming the contents of the array, in-place:
Summing a bunch of numbers:
Even mimicking
forEach()
, if you hate optimized native code:Excellent examples man! reduce() is truly powerful.
can you plz add me i need to talk to you
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
Thanks for the reminder Jon. I had that in mind but didn't bother to put it but now I think I should.