如何使用underscore.js做正序和倒虚排序

StackOverflow地址

http://stackoverflow.com/questions/15137948/how-can-i-do-an-asc-and-desc-sort-using-underscore-js#

问题描述

楼主正在用underscorejs来对我的json数据进行排序。现在需要对数据进行正序和倒序的排序。我查了文档,但是没有找到什么相关内容。怎么搞定这个问题?

最佳解答

你可以用_.sortby,它始终返回一个正序的排序。

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

你也可以使用.reverse方法来得到倒序排序。

1
2
3
4
5
6
var array = _.sortBy([2, 3, 1], function(num) {
return num;
});
console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]

或者在处理数字时给数字加一个负号来得到倒序的列表。

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

再深入解释一下,.sortby使用的是内建的.sort([handler])

1
2
3
4
5
6
7
8
9
// 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;
});