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?
sumvariable. You need to resetsumto get what you expect.