Mr.AZ
Mr.AZ

Reputation: 363

when to use reduce and reduceRight?

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

Upvotes: 33

Views: 16371

Answers (9)

Muad1105
Muad1105

Reputation: 1

The use of reduce() and reduceRight() methods utility is different as the following code shows which is been mentioned in most pages describing the same,

var arr = ["a", "b", "c", "d", "e"];

total1 = arr.reduce(function(prev, cur) {
    return prev + cur;
});

total2 = arr.reduceRight(function(prev, cur) {
     return prev + cur;
});

console.log(total1); // => abcde
console.log(total2); // => edcbe

The purpose of using these two differs as it depends on the functionality you are working on.

Tried to think about some real-world scenarios but failed to reach a perfect example. :)

Upvotes: -1

Sohail Arif
Sohail Arif

Reputation: 275

ReduceRight is different from reduce method as it starts computation on values from right to left.

Reduce Example:

<!doctype html>
<html>

<head>
  <script>
    var arr = [1, 2, 3];
    document.write(arr.reduce(function(x, y) {
      return x * y;
    }, 4));
  </script>
</head>

</html>

Starting from left to right: 12 = 23 = 6 * 4 = 24

ReduceRight Example

<!doctype html>
<html>

<head>
  <script>
    var arr = [4, 256];
    document.write(arr.reduceRight(function(x, y) {
      return x / y;
    }, 1024));
  </script>
</head>

</html>

Starting from right to left: 1024/256 = 4/4 = 1

Upvotes: 4

Shakil Ahmed Omi
Shakil Ahmed Omi

Reputation: 1

Reduce work Left to right. And Reduce Right work from Right to Left.

var arr = ["1", "2", "3", "4", "5", "6"];
let total1 = arr.reduce(arrReduce);
let total2 = arr.reduceRight(arrReduce);
function arrReduce(prevValue, currentValue) {
    return prevValue + currentValue;
}
function reduceRight(prevValue, currentValue) {
    return prevValue + currentValue;
}
console.log(total1);//return 123456
console.log(total2);//return 654321

Upvotes: 0

jsaddwater
jsaddwater

Reputation: 1829

The reverse order is of importance for instance when dealing with HTTP interceptors in Angular. Then you want the last interceptor to be the first in the chain to be executed. I searched for ".reduceRight" on GitHub and found a total of 20 JS repos using it. So basically , You probably don't need to use it.

https://medium.com/dev-proto/how-it-works-array-reduceright-f7dfbd32cc59

Upvotes: -2

zivc
zivc

Reputation: 353

Do correct me if I am wrong;

My understanding is that, solely in the context of Array, the fundamental difference between reduce and reduceRight - other than just the direction - is that in previous moments of history (before browser optimisations etc), compilers would count backwards from 10 to 0, (arr.reduceRight - right-to-left), a lot faster than counting forwards from 0 to 10 (arr.reduce - left-to-right).

Reducing from the right meant that the compiler could start at 10 and the iterator could only ever get to 0. This meant that the compiler, on each iteration, had to check that the current iteration is greater than 0. Easy peasy.

However, when reducing from the left (arr.reduce - left-to-right), the length of the collection could possibly change, and thus the compiler having to re-evaluate arr.length on each iteration.

For an example, if you had an array of 10 using Array(10), and you used arr.reduce() - left-to-right, the compiler would have to check to make sure nothing else is pushed on to the collection during the reduce, in order to determine its position - on each iteration.

I hope this helps someone :)

Upvotes: 5

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

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)  )

Upvotes: 18

Deadpool
Deadpool

Reputation: 8240

The only thing is order of computation. Reduce does it 'left to right', reduceRight does it 'right to left'. See the following example:

<html>

<head></head> 

<body> 

<script>

var a = [200, 100, 2];
var c = a.reduce(function(previousVal, currentVal){ 
previousVal = previousVal / currentVal; 
return previousVal;  
});
var c = a.reduceRight(function(previousVal, currentVal){ 
previousVal = previousVal / currentVal; 
return previousVal;  
});
alert(c);

</script> 

</body> 

</html> 
</html> 

Upvotes: 0

Array.reduceRight() is great when:

  • you need to iterate over an Array of items to create HTML
  • AND need a counter in HTML prior to the items

.

var bands = {
    Beatles: [
        {name: "John", instruments: "Guitar"},
        {name: "Paul", instruments: "Guitar"},
        {name: "George", instruments: "Guitar"},
        {name: "Ringo", instruments: "Drums"}]
};
function listBandplayers(bandname, instrument) {
    var bandmembers = bands[bandname];
    var arr = [  "<B>" , 0 , ` of ${bandmembers.length} ${bandname} play ` , instrument , "</B>",
                "\n<UL>" , ...bandmembers , "\n</UL>" ];
    var countidx = 1;
    return arr.reduceRight((html, item, idx, _array) => {
            if (typeof item === 'object') {
                if (item.instruments.contains(instrument)) _array[countidx]++;
                item = `\n\t<LI data-instruments="${item.instruments}">` + item.name + "</LI>";
            }
            return item + html;
    });
}
console.log( listBandplayers('Beatles', 'Drums') );
/*
<B>1 of 4 Beatles play Drums</B>
<UL>
    <LI data-instruments="Guitar">John</LI>
    <LI data-instruments="Guitar">Paul</LI>
    <LI data-instruments="Guitar">George</LI>
    <LI data-instruments="Drums">Ringo</LI>
</UL>
*/
console.log( listBandplayers('Beatles', 'Guitar') );
/*
<B>3 of 4 Beatles play Guitar</B>
<UL>
    <LI data-instruments="Guitar">John</LI>
    <LI data-instruments="Guitar">Paul</LI>
    <LI data-instruments="Guitar">George</LI>
    <LI data-instruments="Drums">Ringo</LI>
</UL>
*/

Upvotes: 5

Harry He
Harry He

Reputation: 1815

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

Upvotes: 78

Related Questions