Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 18, 2022 11:57 am GMT

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)

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

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.


Original Link: https://dev.to/amiinequ/javascripts-reduce-method-in-a-nutshell-gik

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To