Reputation: 4868
Is there a way to do this out of the box with the _.sortBy method or any other part of the library?
Upvotes: 13
Views: 11845
Reputation: 11003
Since you tagged your question with the backbone.js tag, I'm assuming you mean to sort a collection, you just need to provide a comparator function on your collection and backbone will keep the collection sorted.
If your question is specifically alphabeticical sorting, I believe that is the default sort, from the backbone.js documentation (I linked to it above)
chapters.comparator = function(chapter) {
return chapter.get("page");
};
Upvotes: 10
Reputation: 128307
You mean like this?
var array = [
{ name: "banana" },
{ name: "carrot" },
{ name: "apple" }
];
var sorted = _(array).sortBy("name");
I'd say it works out of the box.
If you wanted to sort an ordinary array of strings, you probably just want to use sort
:
var flatArray = ["banana", "carrot", "apple"];
flatArray.sort();
See here. Also works.
Note that Underscore's sortBy
returns a new array which is sorted, where JavaScript's built-in sort
function sorts an array in place.
Upvotes: 25