1

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

1 Answer 1

3

If you push() to scorelist, I'd be tempted to say it's likely an Array.

You could use reduce().

var total = scorelist.reduce(function(total, score) {
    return total + +score;
}, 0);
Sign up to request clarification or add additional context in comments.

7 Comments

Quite elegant the reduce function.
I'm not sure I really understand the reduce function. would you mind explaining more?
@NicMeiring MDN has good documentation.
thanks. get it now. answer still concatenating instead of summing though. see updates.
@NicMeiring You must be storing scores as strings. I'll update my answer.
|

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.