Can you describe this for me?
var arr, total; arr = [1, 2, 3, 4, 5]; total = arr.reduce(function(previous, current) { return previous + current; }); // total is 15
We use where as a conjunction meaning 'in the place that' or 'in situations that'. The clause with where is a subordinate clause and needs a main clause to complete its meaning. If the where clause comes before the main clause, we use a comma: Where you find a lot of water, you will also find these beautiful insects.
reduceRight() The reduceRight() method applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.
The arr. reduce() method in JavaScript is used to reduce the array to a single value and executes a provided function for each value of the array (from left-to-right) and the return value of the function is stored in an accumulator.
The reduce() method executes a reducer function on each element of the array and returns a single output value.
The order for reduce is from left to right, and it's from right to left for reduceRight, as the following piece of code shows:
var arr = ["1", "2", "3", "4", "5"]; total1 = arr.reduce(function(prev, cur) { return prev + cur; }); total2 = arr.reduceRight(function(prev, cur) { return prev + cur; }); console.log(total1); // => 12345 console.log(total2); // => 54321
In some cases, the difference between reduce
and reduceRight
does matter:
However, because adding two integers is commutative in JavaScript, it doesn't matter in your example, just like how 1 + 2
is equal to 2 + 1
in math.
var arr = ["A", "B", "C", "D", "E"]; console.log( arr.reduce((previous, current) => previous + current) ) console.log( arr.reduceRight((previous, current) => previous + current) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With