25

I am curious as to why previousValue is always undefined in the following code when using .reduce on an array:

Code:

[2,2,2,3,4].reduce(function(previousValue, currentValue){
    console.log("Previous Value: " + previousValue);
    console.log("Current Value: " + currentValue);
},0)

Output:

Previous Value: 0 (index):
Current Value: 2 (index):
Previous Value: undefined (index):
Current Value: 2 (index):
Previous Value: undefined (index):
Current Value: 2 (index):
Previous Value: undefined (index):
Current Value: 3 (index):24
Previous Value: undefined (index):23
Current Value: 4 

A fiddle can be found here: http://jsfiddle.net/LzpxE/

1
  • 6
    You need to return something from the function. This will be the value of previousValue on the next iteration.
    – Matt
    Feb 5, 2014 at 22:35

3 Answers 3

62

You need to return a value in order to use reduce correctly. The returned value will be used in the next step.

Like:

[0,1,2,3,4].reduce(function(previousValue, currentValue) {
     return previousValue + currentValue;
});
// returns 10 in total, because
// 0 + 1 = 1 -> 1 + 2 = 3 -> 3 + 3 = 6 -> 6 + 4 = 10  
0
0

I think it is happening because you are not returning any value from previous iteration of reduce() and he think that his previous value is undefined.

1
  • 1
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
    – Community Bot
    Jun 23, 2022 at 17:49
0

The reduce() function has its callback. The value returned in the callback is the previousValue argument presented in the function signature.

It is not the previous index in the array. If you want previousValue to display the previous element in the array, you can return the current value in the callback:

[12, 23, 34, 45, 56].reduce((previous, current, index, array) => { return current })
1
  • Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Oct 7, 2022 at 3:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.