Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Backbone collection alphabetically

Is there a way to do this out of the box with the _.sortBy method or any other part of the library?

like image 622
Will Hitchcock Avatar asked Jun 28 '12 20:06

Will Hitchcock


People also ask

What is collections in Backbone JS?

Advertisements. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.


1 Answers

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.

like image 140
Dan Tao Avatar answered Oct 16 '22 15:10

Dan Tao