在JS里常常用到排序(包括正序和逆序),特记录下
1.正序
原始数据为:
var test_order = [{order:5, name:"tl1"},{name:"tl2"},{order:4, name:"tl3"},{order:1, name:"tl4"}]
1.1 利用JS的sort()正序排序
test_order.sort(function (a,b) {
console.log("a=" + a.name+";b="+ b.name);
return (a.order||0) - (b.order||0);
});
执行结果是:
[{name: "tl2"},{order: 1, name: "tl4"},{order: 4, name: "tl3"},{order: 5, name: "tl1"}]
==============
实际执行过程是如下这样:
a=tl1;b=tl2
a=tl1;b=tl3
a=tl2;b=tl3
a=tl1;b=tl4
a=tl3;b=tl4
a=tl2;b=tl4
—————————–深入理解sort
关于sort()的详细内容可以参考:http://www.w3schools.com/jsref/jsref_sort.asp
Example
Sort numbers in an array in ascending(up) order:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return a-b});
The result of points will be:
1,5,10,25,40,100
Sort numbers in an array in descending(down) order:
var points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){return b-a});
The result of points will be:
100,40,25,10,5,1
1.2 Lodash 的sortBy 正序排序
Lodash官方网站可以查阅:Lodash docs
例子:
var myArray = [ 3, 4, 2, 9, 4, 2 ];
_.sortBy(myArray);
// → [ 2, 2, 3, 4, 4, 9 ]
_(myArray).sortBy().take(3).value();
// → [ 2, 2, 3 ]
var users = [
{ 'user': 'fred', 'age': 48 },
{ 'user': 'barney', 'age': 36 },
{ 'user': 'fred', 'age': 40 },
{ 'user': 'barney', 'age': 34 }
];
_.sortBy(users, [function(o) { return o.user; }]);
// => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
_.sortBy(users, ['user', 'age']);
// => objects for [['barney', 34], ['barney', 36], ['fred', 40], ['fred', 48]]
2.逆序
2.1 JS原生态的sort进行逆序排序
可以将正序里面的匿名函数返回值前加个负号,或者用后者减去前者也可以实现。比如:
test_order.sort(function (a,b) {
return -(a.order||0) - (b.order||0);
});
//====>等价于
test_order.sort(function (a,b) {
return (b.order||0) - (a.order||0);
});
2.2 Lodash库的orderBy进行逆序排序
As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):
var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);
Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):
var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);
In version 4 of lodash this method has been renamed orderBy:
var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);