JavaScript - examples of reduce() function

2020-03-12 08:11发布

问题:

I'm looking at this example of use of reduce() function.

function add(runningTotal, currentValue) {
   return runningTotal + currentValue;
}

var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add);
print(sum); // displays 55

Could you give show me some other examples of using reduce() - I'm not sure I fully follow how it works.

Thank you

回答1:

What reduces does is take an initialValue, a function with 2 essential parameters (can take more) and a list of values. If no initialValue is provided then it's assumed it's the first element of the list. The function is supposed to do something with the previousValue usually used as an accumulator and the nextValue.

So, assume you have a list of values: [1, 2, 3, 4, 5] and the function is supposed to add the 2 parameters and an initialValue of 0.

First step:

0 + 1 = 1
    2
    3
    4
    5

Second step:

1 + 2 = 3
    3
    4
    5

Third Step:

3 + 3 = 6
    4
    5

Fourth Step:

6 + 4 = 10
    5

Fifth Step:

10 + 5 = 15 //Final value

As you can see, the input went from a list to a single value, hence the name reduce. In your example, there's no initialValue (that's the second argument), so it's as if started on the second step.



回答2:

You can set second argument for reduce

function add(runningTotal, currentValue) {
   return runningTotal + currentValue;
}
var someInitValue = 10
var nums = [1,2,3,4,5,6,7,8,9,10];
var sum = nums.reduce(add, someInitValue);
console.log(sum); // displays 65



回答3:

reduce() works by iterating over an array and calling a reductor function (this function is the first argument passed to reduce(). This function has four arguments:

  • previousValue, which is sort of a 'running total'. this is initially undefined, unless you provide a seed value as the second argument to reduce().
  • currentValue which is an object in your array
  • index of the current value in your array
  • array, the array itself

when your reductor function is called, its return value becomes the new previousValue argument for next time the reductor function is called. that's the magic. after the reductor function is called and given the very last object in the array, its return value will be the return value of reduce().

honestly, a lot of the examples you'll see (like using reduce() to sum up a bunch of integers) are pretty easy to do with a for() loop. its real value is when you're doing functional programming.



回答4:

You can also use reduce to do things like generate some kind of stream cipher.

var plaintext = "thisisaplaintext";
var chars = plaintext.split('');
var result = '';
function encrypt(runningTotal, currentValue){
    var newVal = ((runningTotal + (""+runningTotal).charCodeAt()-32) % 94)+32
    result  = result + String.fromCharCode(newVal)
    return newVal;
}
chars.reduce(encrypt, 15 /*any arbitrary starting value*/);
console.log(result);

Basically, anything that can be made with a combination of independent calculations or anything that requires some rolling total. It's nothing that you couldn't already do with a for loop, but it looks cleaner.