Is there a way to do this out of the box with the _.sortBy method or any other part of the library?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With