Skip to content Skip to sidebar Skip to footer

How To Use Groupby In Backbone.js To Group Collections?

An example collection (showing models only): [ { name: 'Bob' date: 'Thu Mar 29 2012' }, { name: 'James' date: 'Fri Mar 30 2012' },

Solution 1:

If you are grouping an actual backbone collection you can use the backbone method groupBy which implicitly uses underscore _.groupBy functionality. This is a much cleaner approach in my opinion.

collection.groupBy( function(model){
  return model.get('date');
});

Solution 2:

ThiefMaster answer is perfectly valid, but it caused me some confusion because I was searching a solution for a backbone.js collection as the title indicates.

If the question object is a backbone collection we should do the following to group the models by date:

_.groupBy(collection.models, function(model){
    return model.get('date')
});

I hope it helps

Solution 3:

Use _.groupBy(data, 'date');

You could also use pass a custom function, but in this case it's not necessary as the attribute shortcut syntax above works fine.

_.groupBy(data, function(row) {
    return row.date;
});

Demo:

> _.groupBy(data, 'date')
{ 'Thu Mar 29 2012': [ { name: 'Bob', date: 'Thu Mar 29 2012' } ],
  'Fri Mar 30 2012':
   [ { name: 'James', date: 'Fri Mar 30 2012' },
     { name: 'Dylan', date: 'Fri Mar 30 2012' } ],
  'Sat Mar 31 2012': [ { name: 'Stanley', date: 'Sat Mar 31 2012' } ] }
> _.groupBy(data, function(row) { return row.date });
{ 'Thu Mar 29 2012': [ { name: 'Bob', date: 'Thu Mar 29 2012' } ],
  'Fri Mar 30 2012':
   [ { name: 'James', date: 'Fri Mar 30 2012' },
     { name: 'Dylan', date: 'Fri Mar 30 2012' } ],
  'Sat Mar 31 2012': [ { name: 'Stanley', date: 'Sat Mar 31 2012' } ] }
>

Solution 4:

var groups =collection.groupBy(function(model) { return model.get('date'); });

//iterate over groupsfor(dateingroups) { 
    var models = groups[date];
    console.log('date: '+date); 
    for (var model_idx in models) {  
        console.log('    name: '+ models[model_idx].get('name'));
    }
}

Solution 5:

For those using Lodash instead of underscore, you can achieve the same result using the _.method() accessor,

collection.groupBy(_.method('get', 'date'));

Post a Comment for "How To Use Groupby In Backbone.js To Group Collections?"