Search code examples
javascriptbackbone.js

Reverse sort order with Backbone.js


With Backbone.js I've got a collection set up with a comparator function. It's nicely sorting the models, but I'd like to reverse the order.

How can I sort the models in descending order rather than ascending?


Solution

  • Well, you can return negative values from comparator. If we take, for example, the example from Backbone's site and want to reverse the order, it will look like this:

    var Chapter  = Backbone.Model;
    var chapters = new Backbone.Collection;
    
    chapters.comparator = function(chapter) {
      return -chapter.get("page"); // Note the minus!
    };
    
    chapters.add(new Chapter({page: 9, title: "The End"}));
    chapters.add(new Chapter({page: 5, title: "The Middle"}));
    chapters.add(new Chapter({page: 1, title: "The Beginning"}));
    
    alert(chapters.pluck('title'));