Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
    },
    {
        name: "Dylan"
        date: "Fri Mar 30 2012"
    },
    {
        name: "Stanley"
        date: "Sat Mar 31 2012"
    },
]

How can I use Underscore.js' groupBy function to group models with the same date?

like image 987
Mark Nguyen Avatar asked Mar 31 '12 09:03

Mark Nguyen


3 Answers

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');
});
like image 175
bullfrog Avatar answered Nov 16 '22 02:11

bullfrog


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

like image 24
RaTiO Avatar answered Nov 16 '22 02:11

RaTiO


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' } ] }
>
like image 31
ThiefMaster Avatar answered Nov 16 '22 02:11

ThiefMaster