gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:16:55 25 4
gpt4 key购买 nike

我目前正在使用 underscorejs 对我的 json 排序进行排序。现在我要求使用 underscore.js 进行 ascendingdescending 排序。我在文档中没有看到任何相同的内容。我怎样才能做到这一点?

最佳答案

您可以使用 .sortBy ,它总是会返回一个升序列表:

_.sortBy([2, 3, 1], function(num) {
return num;
}); // [1, 2, 3]

但您可以使用 .reverse获取方法降序:

var array = _.sortBy([2, 3, 1], function(num) {
return num;
});

console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]

或者在处理数字时,在返回中添加一个负号来降序:

_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
return -num;
}); // [3, 2, 1, 0, -1, -2, -3]

引擎盖下.sortBy使用内置 .sort([handler]) :

// Default is alphanumeric 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;
});

关于javascript - 如何使用 underscore.js 进行 asc 和 desc 排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15137948/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com