Skip to content

Instantly share code, notes, and snippets.

@procky
Last active October 22, 2021 20:40
Show Gist options
  • Save procky/5a0a3e178ccb87562f07 to your computer and use it in GitHub Desktop.
Save procky/5a0a3e178ccb87562f07 to your computer and use it in GitHub Desktop.
Sort by multiple attributes in a backbone collection in the browser
// A multi columns sort implementation that sorts like SQL ORDER BY.
_.extend(Backbone.Collection.prototype, {
sortOptions: null,
comparator: function(a, b) {
var atts = [], dirs = [], att, i;
if(!this.sortOptions) {
return 0;
}
// take the array of objects {'att':'attName','dir':'dirName'} and put it into two arrays, one for attributes, one for asc/desc
for(i = 0; i < this.sortOptions.length; i++) {
atts.push(this.sortOptions[i].att);
dirs.push(this.sortOptions[i].dir);
}
// look through attributes supplied for any that don't have equal values
att = _.find(atts, function(c) { return a.attributes[c] != b.attributes[c]; });
// if all the values are equal, att is undefined. No need to sort.
if(!att) {
return 0;
}
// use that attribute to determine the order. Match the attributes in order to the methods for asc/desc. default = asc
if((dirs[_.indexOf(atts, att)] || 'asc').toLowerCase() == 'asc') {
return (a.attributes[att] > b.attributes[att]) ? 1 : -1;
} else {
return (a.attributes[att] < b.attributes[att]) ? 1 : -1;
}
}
});
// Example usage:
// PeopleList is a collection that is populated.
// Once sorted, render all the models in the collection again to see the sort working
PeopleList.sortOptions = [{'att':'name','dir':'desc'}, {'att':'age','dir':'asc'}];
PeopleList.sort();
// Based on and many thanks to http://www.benknowscode.com/2013/12/multi-column-sort-in-backbone-collections.html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment