javascript 按字母顺序排序 Backbone 集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11252417/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting Backbone collection alphabetically
提问by Will Hitchcock
Is there a way to do this out of the box with the _.sortBy method or any other part of the library?
有没有办法使用 _.sortBy 方法或库的任何其他部分开箱即用地执行此操作?
采纳答案by Hyman
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 comparatorfunction on your collection and backbone will keep the collection sorted.
由于您使用backbone.js 标签标记了您的问题,我假设您的意思是对集合进行排序,您只需要在集合上提供一个比较器函数,主干将保持集合排序。
If your question is specifically alphabeticical sorting, I believe that is the default sort, from the backbone.js documentation (I linked to it above)
如果您的问题是专门按字母顺序排序,我相信这是来自backbone.js 文档的默认排序(我在上面链接到了它)
chapters.comparator = function(chapter) {
return chapter.get("page");
};
回答by Dan Tao
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
:
如果您想对普通的字符串数组进行排序,您可能只想使用sort
:
var flatArray = ["banana", "carrot", "apple"];
flatArray.sort();
See here. Also works.
见这里。也有效。
Note that Underscore's sortBy
returns a newarray which is sorted, where JavaScript's built-in sort
function sorts an array in place.
请注意,UnderscoresortBy
返回一个已排序的新数组,JavaScript 的内置sort
函数在其中对数组进行原地排序。