Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using underscore to sort a collection based on date

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

like image 289
Chapsterj Avatar asked Mar 02 '12 21:03

Chapsterj


1 Answers

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/

like image 185
mu is too short Avatar answered Oct 06 '22 12:10

mu is too short