Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when to use reduce and reduceRight?

Tags:

javascript

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 
like image 784
Mr.AZ Avatar asked Dec 24 '13 01:12

Mr.AZ


People also ask

Where do we use reduce?

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.

What is reduceRight?

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.

What is array reduce used for?

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.

What does the reduce method do?

The reduce() method executes a reducer function on each element of the array and returns a single output value.


2 Answers

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 
like image 140
Harry He Avatar answered Oct 16 '22 17:10

Harry He


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)  )
like image 22
Qantas 94 Heavy Avatar answered Oct 16 '22 17:10

Qantas 94 Heavy