when to use reduce and reduceRight?

前端 未结 6 2064
野性不改
野性不改 2020-12-17 08:44

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         


        
相关标签:
6条回答
  • 2020-12-17 08:56

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

    Reference: http://www.thesstech.com/javascript/array_redcueright_method

    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: 1*2 = 2*3 = 6 * 4 = 24

    Ref:http://www.thesstech.com/tryme?filename=javascript_array_reduce_method

    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

    Ref:http://www.thesstech.com/tryme?filename=javascript_array_reduceright_method

    0 讨论(0)
  • 2020-12-17 08:59

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

    0 讨论(0)
  • 2020-12-17 09:01

    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>
    */
    
    0 讨论(0)
  • 2020-12-17 09:09

    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
    
    0 讨论(0)
  • 2020-12-17 09:10

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

    0 讨论(0)
  • 2020-12-17 09:20

    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> 

    0 讨论(0)
提交回复
热议问题