I want to sum a list of numbers stored in a JavaScript object. The object is created and updated using this code:
var myscore = $('input[name="Points1"]').val();
scorelist = JSON.parse(localStorage.getItem(playerName + 'scorelist') || '[]');
scorelist.push(myscore);
localStorage.setItem(playerName + 'scorelist', JSON.stringify(scorelist));
$('div.scorecolumn', column).html("Score: <br>" + scorelist.join('<br>') + "<br>");
Basically I take whatever is in the column at the time, parse it, add myscore
, stringify it, join each element with a <br>
and write the list to the scorecolumn. The list of numbers is saved as an object. My goal is to sum up all the numbers in the object at any given time.
This script is inside of a function that passes in a bunch of parameters which is why some variables look undefined here.
Any help would be greatly appreciated! Thanks
UPDATE:
var nicTotalScore = nicScoreList.reduce(function(score, total) {
return total + score;
}, 0);
console.log(nicTotalScore); //12120
console.log(nicScoreList); //["12", "12"]
UPDATE: If the score field is left blank when submitted, an empty string " " instead of a score. this is registering as a 0 when the reduce method goes through the array. This doesnt affect the total, but say, for example, i wanted to then find the average score, it throws it off. any ideas there? thanks
If you
push()
toscorelist
, I'd be tempted to say it's likely anArray
.You could use
reduce()
.