最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript - examples of reduce() function - Stack Overflow

programmeradmin3浏览0评论

I'm looking at this example of use of the 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.

I'm looking at this example of use of the 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.

Share Improve this question edited Jul 6, 2023 at 22:39 Mehdi Charife 1,0243 gold badges9 silver badges28 bronze badges asked Jan 4, 2016 at 22:19 WastelandWasteland 5,37915 gold badges56 silver badges97 bronze badges 6
  • Any other example is likely to confuse you more. That example is the most basic, easily understood use. – Barmar Commented Jan 4, 2016 at 22:23
  • 1 Take a look at this. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Shyju Commented Jan 4, 2016 at 22:24
  • The actual implementation of Array.prototype.reduce may give yet more info: github.com/v8/v8/blob/70c4bf13315145be89e9f8b7f4313fab2442dcda/… – zerkms Commented Jan 4, 2016 at 22:27
  • I'm just confused on what reduce() does. The add() function confuses me as well. The add function requires 2 arguments but when fed to the reduce function, add function has no argument. Would you explain in works how it all works? – Wasteland Commented Jan 4, 2016 at 22:27
  • That's because it's a reference to a function passed to the nums.reduce(). Then the Array.prototype.reduce implementation takes that reference to a function and invokes it on every element (and passes 4 arguments to be precise). – zerkms Commented Jan 4, 2016 at 22:29
 |  Show 1 more comment

4 Answers 4

Reset to default 11

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.

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

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.

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.

发布评论

评论列表(0)

  1. 暂无评论