1

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?

1
  • You just keep adding to sum variable. You need to reset sum to get what you expect. Commented Jan 19, 2016 at 18:08

2 Answers 2

3

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);
};
Sign up to request clarification or add additional context in comments.

2 Comments

What does previousValue represent? The previous return?
@komali_2: When you are reducing with the reduce argument, the previousValue is the value that was returned from the previous iteration of the cycle (or your seed value for the first iteration).
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.