如何使用underscore.js进行asc和desc排序?

Rah*_*hul 161 javascript underscore.js

我目前正在使用underscorejs来排序我的json排序.现在我要求做的ascendingdescending排序使用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)

  • 最后的解决方案,即为返回的num添加negetive符号是完美的. (9认同)

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)

  • +1以避免`array.reverse`操作 (6认同)
  • charCodeAt将"返回字符串中指定索引处的字符的Unicode",因此它可以用于按字符串中的字符排序,但是如图所示它*不*"按字符串排序"它按字符串排序串 (4认同)
  • 我试图按字母顺序排序 - 乘以-1不是有效的操作.:) (3认同)
  • 这仅按第一个字符排序,并且区分大小写. (2认同)

Emi*_*erg 47

所述阵列原型的反向方法修改该阵列,并返回对它的引用,这意味着你可以这样做:

var sortedAsc = _.sortBy(collection, 'propertyName');
var sortedDesc = _.sortBy(collection, 'propertyName').reverse();
Run Code Online (Sandbox Code Playgroud)

此外,下划线文档如下:

此外,Array原型的方法通过链接的Underscore对象进行代理,因此您可以将a reverse或a push滑入链中,并继续修改数组.

这意味着你也可以.reverse()在链接时使用:

var sortedDescAndFiltered = _.chain(collection)
    .sortBy('propertyName')
    .reverse()
    .filter(_.property('isGood'))
    .value();
Run Code Online (Sandbox Code Playgroud)

  • 在性能方面,最好首先应用过滤器,然后排序(剩余的)值. (5认同)
  • 要做一个不区分大小写的字母排序:`_.sortBy(collection,item => item.propertyName.toLowerCase());` (2认同)

Min*_*ain 11

与Underscore库类似,还有另一个名为"lodash"的库,它有一个方法"orderBy",它接受参数来确定对它进行排序的顺序.你可以像使用它一样

_.orderBy('collection', 'propertyName', 'desc')
Run Code Online (Sandbox Code Playgroud)

出于某种原因,它没有在网站文档中记录.