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?
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');
});
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
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' } ] }
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With