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