1

I am working on a backbone application at the moment, and I wanting to order my collection based on various attributes, I have sorting working based on cost, duration, start and finish date (timestamps) but I am struggling to sort the collection based on the name attribute, here is my collection code,

var ProjectCollection = Backbone.Collection.extend({

   url: '/projects',
   model: app.Project,
   sort_key: "finish_date",
   sort_order: 1,
   parent_filter: false,

   initialize: function() {
       var pm = this.get('projectmanager');
       this.set("project_manager", new app.User(pm));

       var sp = this.get('salesperson');
       this.set("sales_person", new app.User(sp));
   },

   comparator: function (item1, item2) {
       return (item1.get(this.sort_key) - item2.get(this.sort_key)) * this.sort_order;
   },

   sortByField: function(fieldName, orderType) {
       this.sort_key = fieldName;
       this.sort_order = orderType == "desc" ? -1 : 1;
       console.log(this.sort_order);
       this.sort();
  },

});

Is there are way to sort alphabetically on a string?

I have added the new comparator function, and this is output I get when ordering via name in an ascending fashion,

Android Application
Hello World I am a new instance of a project
Java Application
Simon's Project
Some new project
Symfony App, Windows Application iPhone Application

As you can see iPhone application should not be last in the list.

Udders
  • 6,914
  • 24
  • 102
  • 194

1 Answers1

2

i changed your comprator function to support strings along with numerics the problem in your comprator function is that it subtracting strings which yields NaN i changed it to be like

comparator: function (item1, item2) {
    var sortValue = (item1.get(this.sort_key) > item2.get(this.sort_key)) ? 1 : -1;
    return sortValue * this.sort_order;
},

this will just compare, get a value 1 for a > b and then change it for desc sort like you did

check this jsFiddle

EDIT: to support case insensitive ordering, comparator function should be modified to handle strings separately

comparator: function (item1, item2) {
        var val1 = item1.get(this.sort_key);
        var val2 = item2.get(this.sort_key);
    if (typeof (val1) === "string") {
        val1 = val1.toLowerCase();
        val2 = val2.toString().toLowerCase();
    }

    var sortValue = val1 > val2 ? 1 : -1;
    return sortValue * this.sort_order;
} 

jsFiddle updated

mfarouk
  • 644
  • 5
  • 14
  • this happened because of the iPhone starts in lower case, i think we should modify the comparator function to handle strings separately, i will check and be back – mfarouk Nov 06 '14 at 06:55