如何使用underscore.js进行asc和desc排序? [英] How can I do an asc and desc sort using underscore.js?

查看:206
本文介绍了如何使用underscore.js进行asc和desc排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

您可以使用 .sortBy ,它将始终返回升序列表:

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

但你可以使用。reverse 方法将其降序

But you can use the .reverse method to get it descending:

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]

引擎盖 .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;
});

这篇关于如何使用underscore.js进行asc和desc排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆