Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone/Underscore sortBy is not sorting collection

I have a list of users (six to be exact) in a collection with 'firstname', 'lastname' properties. Doing a fetch, the comparator below sorts them by 'firstname', and it works fine.

comparator : function (user) {
  return user.get("firstname").toLowerCase();
}

But if I try to sort the collection later, by a different value i.e. 'lastname', it doesn't work. The order stays the same.

this.collection.sortBy(function(user) {
  return user.get("lastname").toLowerCase();
});

What am i doing wrong?


Update


So the data returned from sortBy IS sorted but that doesn't help me really as my view is linked to the collection. If i reset the collection and add the sorted array back to the collection it's comparator does it's job and sorts it back into 'firstname' order.

var sorted = this.collection.sortBy(function(user) {
  return user.get("lastname").toLowerCase();
});
like image 842
screenm0nkey Avatar asked Mar 21 '12 11:03

screenm0nkey


People also ask

How to use_ sortBy?

The _. sortBy() function is used to sort all the elements of the list in ascending order according to the function given to it as a parameter. Passing the array with a function which returns the number and it will sort the array in ascending order and return an array.

How sortBy works?

The sort() method sorts the elements of an array in place and returns the reference to the same array, now sorted. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.


2 Answers

To respond to your update:

If you're wanting to change the order that the collection is sorted in for use by it's corresponding view then you could just update the comparator and then call sort to get the model re-sorted. This will then fire a sort event which your view can listen for and update itself accordingly.

this.collection.comparator = function (user) {
  return user.get("firstname").toLowerCase();
};

this.collection.sort();
like image 151
obmarg Avatar answered Oct 29 '22 11:10

obmarg


The sortBy function does not sort the objects in the current collection. It returns a sorted collection:


var sortedCollection = this.collection.sortBy(function(user){
  return user.get("lastname").toLowerCase();
});

Now you can use sortedCollection and it will be sorted correctly.

like image 38
Derick Bailey Avatar answered Oct 29 '22 13:10

Derick Bailey