简体   繁体   中英

Javascript .reduce() not functioning as expected?

I'm attempting to create a function that takes an array as an argument, then multiplies each element of the array by its index, then sums together and returns those values. However, I'm getting returns that I can't explain.

var sum = 0;
function crazy_sum(numbers){
 return numbers.reduce(function(previousValue,currentValue,currentIndex,array){
        sum += currentValue*currentIndex;
        return sum;
    },0);
};


console.log(crazy_sum([2])); //returns 0, as expected
console.log(crazy_sum([2,3])); //returns 3, as expected
console.log(crazy_sum([2,3,5])); //returns 16 when I would expect 13
console.log(crazy_sum([2,3,5,2])); //returns 35 when I would expect 19

Why am I not getting the results I would expect? What is the function actually doing?

You don't need sum , use the previousValue argument:

function crazy_sum(numbers){
 return numbers.reduce(function(previousValue,currentValue,currentIndex,array){
        previousValue+= currentValue*currentIndex;
        return previousValue;
    },0);
};

There seems to be a fundamental misunderstanding about how reduce works. The answers currently do not reflect the simplicity of reduce.

When using reduce what you're providing are 2 arguments - a function callback, and a starting value.

callback arguments

  • previousValue: this is the value that is being collected as you iterate through the array. It's not really "previous" - it's actually quite current. It's more accurate to call this the "currentTotal" than previous value.
  • currentValue: this just means its the current value in our iteration
  • indexValue: index of the currentValue
  • array: the array you're iterating over.

With this information we can simplify your operation

function crazy_sum(numbers){
    return numbers.reduce(function(currentTotal,currentValue,currentIndex){
        return currentTotal + currentValue * currentIndex;
    }, 0);
}

For more information on reduce check out the docs

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM