0
homeTeam = this.collection.where({teamName: 'Bulls'});

var totalPoints = [];
_.each(homeTeam, function(team) {
    var total = team.get('points');
    totalPoints.push(total);
});

var sum = _.reduce(totalPoints, function(memo, num){ return memo + num; }, 0);
console.log(sum);

In the above I am trying to get the total amount of points the home team has, by iterating through that attribute, then pushing those values into an array. Finally I am using underscore.js's _.reduce method, but I am not getting the right number in the console.

The actual points are 10,12,18,3,0,0 and when I console.log(sum) I get 0101218300, so it turns all those seperate numbers into one gigantic number not by adding the sum but just combining them.

So obviously I am missing something, hopefully there is a better way to add attributes than the way I am doing it.

kay.one
  • 7,622
  • 6
  • 55
  • 74
Michael Joseph Aubry
  • 12,282
  • 16
  • 70
  • 135

1 Answers1

2

It's happening because total points is stored as an array of string. try

.each(homeTeam, function(team) {
    //convert the string to int
    var total = parseInt(team.get('points'),10);
    totalPoints.push(total);
});
kay.one
  • 7,622
  • 6
  • 55
  • 74
  • I removed the 10 and it worked the same, is it vital to have it there, because I have not seen that yet, and don't understand why it's there. – Michael Joseph Aubry Jan 24 '14 at 18:06
  • 1
    @MichaelJosephAubry http://stackoverflow.com/questions/850341/how-do-i-work-around-javascripts-parseint-octal-behavior – nikoshr Jan 24 '14 at 18:07
  • 2
    You should really think twice before removing the second argument 10 as it's really important.https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt#Octal_interpretations_with_no_radix – kay.one Jan 24 '14 at 18:08
  • Okay thats all I wanted to hear, thanks for the links! – Michael Joseph Aubry Jan 24 '14 at 18:08