Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewdeandrade/950240 to your computer and use it in GitHub Desktop.
Save andrewdeandrade/950240 to your computer and use it in GitHub Desktop.
Reverse Alphabetical Sort in Backbone.js
// Assumption: You have a model with a name.
comparator: function (User) {
if (User.get("name")) {
var str = User.get("name");
str = str.toLowerCase();
str = str.split("");
str = _.map(str, function(letter) { return String.fromCharCode(-(letter.charCodeAt(0))) });
return str;
};
}
@stilist
Copy link

stilist commented May 24, 2013

Exactly what I needed, thanks!

@jjhamshaw
Copy link

Really useful, thanks!

@fcsonline
Copy link

I was dealing with this too.

jashkenas/backbone#3117

@braddunbar
Copy link

Backbone comparators can also take two arguments, which allows you to sort in reverse fairly easily with better performance.

Backbone.Collection.extend({

  comparator: function(a, b) {
    return -a.get('name').localeCompare(b.get('name'));
  }

});

Edit: Actually, it's even easier using String#localeCompare.

@BastinRobin
Copy link

How can i switch between asc and desc order in sorting collections

@bryancallahan
Copy link

I know this is a little old @BastinRobin but if others stumble upon this, like I did, here's a little more code for clarity on the whole asc/desc bit.

Backbone.Collection.extend({
  comparator: function(a, b) {
    var direction = 1;  // Asc
    var direction = -1; // Desc
    return direction * a.get('name').localeCompare(b.get('name'));
  }
});

For additional help on localeCompare check out: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

@jfbrennan
Copy link

My production example using @bryancallahan's suggestion:

// Presenter/Controller
function sortUsers() {
    users.sortDirection = $usersView.hasClass('asc') ? -1 : 1;  // dsc : asc
    $usersView.toggleClass('asc')
    users.sort();
}

// Collection
App.UserCollection = Backbone.Collection.extend({
    comparator: function(a, b) {
        return this.sortDirection * a.get('name').localeCompare(b.get('name'));
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment