0

I am iterating through a collection and calling an attribute that is a numeric value, instead of just showing each value one by one, how do I add them all up into one total sum?

playersCollection.each(function(player) {
    var allPoints = player.get('points');
    alert(allPoints);
});

Above returns like

 0
 10
 5
 3

Instead I want to add those numbers so I get

18 
Michael Joseph Aubry
  • 12,282
  • 16
  • 70
  • 135

2 Answers2

2

You will need to keep the allPoints variable outside of the scope of the each() callback function.

var allPoints = 0;
playersCollection.each(function(player) {
    allPoints = allPoints + player.get('points');
});
alert(allPoints);

That should provide you with a Total

Chris Seufert
  • 819
  • 1
  • 7
  • 17
2

This is a classic reduce:

var allPoints = playersCollection.reduce(function(sum, player) {
    return sum + player.get('points');
}, 0);

Demo: http://jsfiddle.net/ambiguous/uqm6J/

Backbone collections have various Underscore methods mixed in, one of those is _.reduce. Any time you want to feed the result of a computation back to itself, you want to look at reduce and you can think of a + b + c + d as (((0 + a) + b) + c) + d, the parentheses outline the feedback.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • nice, I came across reduce, but it's nice to see it in my context makes more sense now. – Michael Joseph Aubry Dec 19 '13 at 07:01
  • You can use [`_.chain`](http://underscorejs.org/#chain) and [`_.filter`](http://underscorejs.org/#filter): `c.chain().filter(...).reduce(...).value()`. – mu is too short Dec 19 '13 at 07:09
  • `var allPoints = playersCollection.where({team: 'Ballaz'}).reduce(function(sum, player) { return sum + player.get('points'); }, 0);` I ran this? I will be changing the 'Ballaz' string to a variable though when it's ready. – Michael Joseph Aubry Dec 19 '13 at 07:09