本文是用typescript写的,跟普通js查不多,稍改造即可
单字段排序
dest.sort(this.getCompareFun(attr1, attr2, orderby));
getCompareFun(attr1, sort) {
return function (o, p) {
let a, b;
if (typeof o === "object" && typeof p === "object" && o && p) {
a = o[attr1];
b = p[attr1];
if (sort == 'asc') {
let result = a < b ? -1 : 1;
return result;
} else {
let result = a > b ? -1 : 1;
return result;
}
}
else {
throw ("error");
}
}
}
多字段排序:
getCompareFun(attr1, attr2, sort) {
return function (o, p) {
let a, b;
if (typeof o === "object" && typeof p === "object" && o && p) {
a = o[attr1];
b = p[attr1];
if (a === b) {
//相同时,按原始顺序升序排列,即Index顺序升序
a = o[attr2];
b = p[attr2];
}
if (sort == 'asc') {
let result = a < b ? -1 : 1;
return result;
} else {
let result = a > b ? -1 : 1;
return result;
}
}
else {
throw ("error");
}
}
}