Chapsterj
Chapsterj

Reputation: 6625

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

Upvotes: 10

Views: 16800

Answers (2)

Gary Rogers
Gary Rogers

Reputation: 405

If you have strings with date info you can....

C = Backbone.Collection.extend({
///...
    comparator: function(m) {
        return -Date.parse(m.get('datestring'));
    }
});

Upvotes: 3

mu is too short
mu is too short

Reputation: 434775

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/

Upvotes: 36

Related Questions