Michael Joseph Aubry
Michael Joseph Aubry

Reputation: 13402

Addition of attributes backbone.js

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.

Upvotes: 0

Views: 63

Answers (1)

kay.one
kay.one

Reputation: 7692

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);
});

Upvotes: 2

Related Questions