javascript 如何使用 underscore.js 进行 asc 和 desc 排序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15137948/
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
How can I do an asc and desc sort using underscore.js?
提问by Rahul
I am currently using underscorejs for sort my json sorting. Now I have asked to do an ascending
and descending
sorting using underscore.js. I do not see anything regarding the same in the documentation. How can I achieve this?
我目前正在使用 underscorejs 对我的 json 排序进行排序。现在我要求做的ascending
和descending
排序使用underscore.js。我在文档中没有看到任何与此相关的内容。我怎样才能做到这一点?
回答by andlrc
You can use .sortBy
, it will always return an ascendinglist:
您可以使用.sortBy
,它将始终返回一个升序列表:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
But you can use the .reversemethod to get it descending:
但是你可以使用.reverse方法让它降序:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Or when dealing with numbers add a negative sign to the return to descend the list:
或者在处理数字时向返回值添加一个负号以降低列表:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Under the hood .sortBy
uses the built in .sort([handler])
:
在引擎盖下.sortBy
使用内置的.sort([handler])
:
// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]
// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
// a = current item in array
// b = next item in array
return b - a;
});
回答by jEremyB
Descending order using underscore can be done by multiplying the return value by -1.
使用下划线的降序可以通过将返回值乘以 -1 来完成。
//Ascending Order:
_.sortBy([2, 3, 1], function(num){
return num;
}); // [1, 2, 3]
//Descending Order:
_.sortBy([2, 3, 1], function(num){
return num * -1;
}); // [3, 2, 1]
If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.
如果您按字符串而不是数字排序,则可以使用 charCodeAt() 方法来获取 unicode 值。
//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){
return s.charCodeAt() * -1;
});
回答by Emil Lundberg
The Array prototype's reverse methodmodifies the array and returns a reference to it, which means you can do this:
所述阵列原型的反向方法修改该阵列,并返回到它的基准,这意味着你可以这样做:
var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();
Also, the underscore documentation reads:
此外,下划线文档如下:
In addition, the Array prototype's methodsare proxied through the chained Underscore object, so you can slip a
reverse
or apush
into your chain, and continue to modify the array.
此外,Array 原型的方法通过链接的 Underscore 对象进行代理,因此您可以将 a
reverse
或 apush
滑入您的链中,并继续修改数组。
which means you can also use .reverse()
while chaining:
这意味着您还可以.reverse()
在链接时使用:
var sortedDescAndFiltered = _.chain(collection)
.sortBy('propertyName')
.reverse()
.filter(_.property('isGood'))
.value();
回答by Minkesh Jain
Similar to Underscore library there is another library called as 'lodash' that has one method "orderBy" which takes in the parameter to determine in which order to sort it. You can use it like
与 Underscore 库类似,还有另一个名为 'lodash' 的库,它有一个方法“orderBy”,它接受参数来确定排序的顺序。你可以像这样使用它
_.orderBy('collection', 'propertyName', 'desc')
For some reason, it's not documented on the website docs.
出于某种原因,它没有记录在网站文档中。
回答by RoboBear
Underscore Mixins
下划线混合
Extending on @emil_lundberg's answer, you can also write a "mixin" if you're using Underscore to make a custom function for sorting if it's a kind of sorting you might repeat in an application somewhere.
扩展@emil_lundberg 的回答,如果您使用 Underscore 制作自定义排序函数,如果它是一种您可能会在某个应用程序中重复的排序,您还可以编写“mixin”。
For example, maybe you have a controller or view sorting results with sort order of "ASC" or "DESC", and you want to toggle between that sort, you could do something like this:
例如,也许您有一个控制器或查看排序结果的排序顺序为“ASC”或“DESC”,并且您想在该排序之间切换,您可以执行以下操作:
Mixin.js
Mixin.js
_.mixin({
sortByOrder: function(stooges, prop, order) {
if (String(order) === "desc") {
return _.sortBy(stooges, prop).reverse();
} else if (String(order) === "asc") {
return _.sortBy(stooges, prop);
} else {
return stooges;
}
}
})
Usage Example
使用示例
var sort_order = "asc";
var stooges = [
{name: 'moe', age: 40},
{name: 'larry', age: 50},
{name: 'curly', age: 60},
{name: 'July', age: 35},
{name: 'mel', age: 38}
];
_.mixin({
sortByOrder: function(stooges, prop, order) {
if (String(order) === "desc") {
return _.sortBy(stooges, prop).reverse();
} else if (String(order) === "asc") {
return _.sortBy(stooges, prop);
} else {
return stooges;
}
}
})
// find elements
var banner = $("#banner-message");
var sort_name_btn = $("button.sort-name");
var sort_age_btn = $("button.sort-age");
function showSortedResults(results, sort_order, prop) {
banner.empty();
banner.append("<p>Sorting: " + prop + ', ' + sort_order + "</p><hr>")
_.each(results, function(r) {
banner.append('<li>' + r.name + ' is '+ r.age + ' years old.</li>');
})
}
// handle click and add class
sort_name_btn.on("click", function() {
sort_order = (sort_order === "asc") ? "desc" : "asc";
var sortedResults = _.sortByOrder(stooges, 'name', sort_order);
showSortedResults(sortedResults, sort_order, 'name');
})
sort_age_btn.on('click', function() {
sort_order = (sort_order === "asc") ? "desc" : "asc";
var sortedResults = _.sortByOrder(stooges, 'age', sort_order);
showSortedResults(sortedResults, sort_order, 'age');
})
Here's a JSFiddle demonstrating this: JSFiddle for SortBy Mixin
这是一个 JSFiddle 演示:JSFiddle for SortBy Mixin