Search code examples
javascriptjquerysortingbackbone.jsunderscore.js

Alphabetically sorting a backbone collection using a key


I have a collection that needs to be sorted by on a particular key ('display'), I know that backbone has a default comparator that is not defined by default, but I am at a loss of how to actually implement it

 var listCollection = new Backbone.Collection(rebuiltArray.map(function(text){
  return {
    attribute: text,
    displayNames: displayNames[text]
  };

 }));

Thanks in advance for your help


Solution

  • Try the following

     var ListCollection = Backbone.Collection.extend({
         comparator: 'displayNames'
     });
    
     var listCollection = new ListCollection(rebuiltArray.map(function(text){
        return {
            attribute: text,
            displayNames: displayNames[text]
        };
     }));