Rah*_*hul 161 javascript underscore.js
我目前正在使用underscorejs来排序我的json排序.现在我要求做的ascending和descending排序使用underscore.js.我在文档中没有看到任何相同的内容.我怎样才能做到这一点?
and*_*lrc 356
您可以使用.sortBy,它将始终返回升序列表:
_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
但是你可以使用.reverse方法让它下降:
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]
Run Code Online (Sandbox Code Playgroud)
或者在处理数字时,在返回时添加一个负号以下降列表:
_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]
Run Code Online (Sandbox Code Playgroud)
引擎盖下.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;
});
Run Code Online (Sandbox Code Playgroud)
jEr*_*myB 57
使用下划线的降序可以通过将返回值乘以-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]
Run Code Online (Sandbox Code Playgroud)
如果您按字符串而不是数字排序,则可以使用charCodeAt()方法获取unicode值.
//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){
return s.charCodeAt() * -1;
});
Run Code Online (Sandbox Code Playgroud)
Emi*_*erg 47
所述阵列原型的反向方法修改该阵列,并返回对它的引用,这意味着你可以这样做:
var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();
Run Code Online (Sandbox Code Playgroud)
此外,下划线文档如下:
此外,Array原型的方法通过链接的Underscore对象进行代理,因此您可以将a
reverse或apush滑入链中,并继续修改数组.
这意味着你也可以.reverse()在链接时使用:
var sortedDescAndFiltered = _.chain(collection)
.sortBy('propertyName')
.reverse()
.filter(_.property('isGood'))
.value();
Run Code Online (Sandbox Code Playgroud)
Min*_*ain 11
与Underscore库类似,还有另一个名为"lodash"的库,它有一个方法"orderBy",它接受参数来确定对它进行排序的顺序.你可以像使用它一样
_.orderBy('collection', 'propertyName', 'desc')
Run Code Online (Sandbox Code Playgroud)
出于某种原因,它没有在网站文档中记录.