Reputation: 342
I cant figure out why array.reduce will return the correct sum on the first pass, but returns NaN on the next passes. Can anyone shed some light as to why this is happening?
Edit - i need to explain, im trying to have a new array with each one adding to the previous value. so
[1, 2, 3, 4] becomes [1, 3, 6, 10]
Right now it comes out [1,3,nan,nan]
Working fiddle https://jsfiddle.net/env4c02b/1/
var numbers = [1, 2, 6, 4];
function getSum(total, currentValue, currentIndex, arr) {
var newVal = Number(total) + Number(currentValue)
total.push(newVal);
return total;
}
var display = numbers.reduce(getSum, [])
document.getElementById("show").innerHTML = display
Upvotes: 0
Views: 324
Reputation: 11806
What are you trying with Number(ARRAY)
? If you try to convert an array to a number, you will have a problem as is a non-sense conversion (like apples to a table). You want to get the last added number of the array and sum it:
var numbers = [1, 2, 3, 4];
function getSum(total, currentValue, currentIndex, arr) {
var newVal = currentValue; // The new value is the current number
if (currentIndex > 0) { // If we are in the second position or more, sum the last value, which is the curent position minus one.
newVal += total[currentIndex-1];
}
total.push(newVal);
return total;
}
var display = numbers.reduce(getSum, []);
document.getElementById("show").innerHTML = display
Upvotes: 1