排序问题
function compare(name, minor) {
return function (o, p) {
var a, b;
if (o && p && typeof o === 'object' && typeof p === 'object') {
a = o[name];
b = p[name];
if (a === b) {
return typeof minor === 'function' ? minor(o, p) : 0;
}
if (typeof a === typeof b) {
return a < b ? -1 : 1;
}
return typeof a < typeof b ? -1 : 1;
} else {
alert("error");
}
}
}
使用方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
//测试数据 data: [{ name: '李寻欢' , age: 32, rank: 1 }, { name: '谢晓峰' , age: 28, rank: 4 }, { name: '潇十一郎' , age: 27, rank: 5 }, { name: '楚留香' , age: 29, rank: 3 }, { name: '傅红雪' , age: 35, rank: 2 } ] //先根据rank排序,再根据age排序,最后根据name排序 data.sort(compare( 'rank' , compare( 'age' , compare( 'name' )))); |
原文地址:https://www.cnblogs.com/zuochengsi-9/p/8492897.html