0
votes

I have a view that should render models for the player who has the maximum points between all the teams. There are many ways to do this but here is the path I am leading down.

getMax : function(attribute) {
    return this.collection.max(function (team) {
        //return team.get('players').get(attribute);
        var test = new PlayersCollection(team.get('players'));
        console.log(test)
    }, this);
},

This is in a marionette collectionView for teams (well composite, but it works like a collection). I understand why test returns the players for each team, but I can't think of a way to merge all the players into one collection then query who is the max points leader.

That said I may be able to avoid merging them in the first place if there is a way to determine who is the leader, but since the collection is nested I am a little stumped.

Since this.collection are the Teams, I thought something like this.collection.get('players').get('points') would allow me to get the max value of all the teams, but that didn't work.

Weird solution 1 I did a little hacking and came up with this. Alot of problems with this because Its stripped of backbone functionality meaning I cant return the model of the max player, only the points of that player, thats it.. still thinking (brain bleeding lol)

teams = App.data.teams

var points1 = teams.get('5368dcc1227a937829b2cb4a').players.pluck('points')
console.log(points1)

var points2 = teams.get('5368dcd9227a937829b2cb4c').players.pluck('points')
console.log(points2)

var test = points1.concat(points2);
console.log(test)

var maxi = _.max(test);

console.log(maxi)

Slightly better solution 2 merging the object arrays

teams = App.data.teams

var home = teams.get('5368dcc1227a937829b2cb4a').players.models;
var away = teams.get('5368dcd9227a937829b2cb4c').players.models;

all = home.concat(away);

console.log(all)
2

2 Answers

1
votes

I think what you are looking for is something like this:

 _.max(this.collection.get('players').pluck('points'));
0
votes

Okay so I think I managed to create a somewhat elegant solution, playing in the console can really teach you a lot (highly recommended if you want to get better).

teams = App.data.teams

var home = teams.get('5368dcc1227a937829b2cb4a').players.models;
var away = teams.get('5368dcd9227a937829b2cb4c').players.models;

all = home.concat(away);
leaders = new PlayersCollection(all)

function mostPoints() {
    return leaders.max(function(leader) {
        return leader.get('points');
    });
}

mostPoints(); 

Now the function will return the model of the player who has the most points out of everyone, pretty cool!