I have a backbone collection which has a bunch of models with date attributes associated with to them. I want to sort them based on their dates. So the latest dates first and so on. Whats the best way to go around this.
The dates are formatted like this, a basic date object. Date {Mon Mar 05 2012 23:30:00 GMT-0500 (EST)}
Thanks
You have Date objects so you can use getTime
to convert them to numbers and then negate those numbers to get the most-recent dates first. If you want to keep your collection sorted then a comparator like this:
C = Backbone.Collection.extend({
//...
comparator: function(m) {
return -m.get('date').getTime();
}
});
will do the trick. Demo (open your console please): http://jsfiddle.net/ambiguous/htcyh/
Backbone collections also include Underscore's sortBy
so you could do a one-time sort:
var sorted = c.sortBy(function(m) { return -m.get('date').getTime() });
Demo: http://jsfiddle.net/ambiguous/FF5FP/
Or you could use toArray
to get a normal JavaScript array and use the standard sort
without using getTime
:
var sorted = c.toArray().sort(function(a, b) {
a = a.get('date');
b = b.get('date');
if(a > b)
return -1;
if(a < b)
return 1;
return 0;
});
Demo: http://jsfiddle.net/ambiguous/QRmJ4/
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