- 多字段同时排序在后端很好实现,直接order by field1 asc, field2 asc,field3 desc…
- 如下可实现在前端按照多字段同时排序:
var items = [
{name:"linc",age:28,num:1234},
{name:"linc",age:28,num:12345},
{name:"kiki",age:20,num:12345},
{name:"高峰",age:26,num:123},
{name:"高峰",age:27,num:101},
{name:"高峰",age:26,num:111},
{name:"安迪",age:29,num:110},
{name:"安迪",age:30,num:110}
];
(function asc-desc(){
items.sort(function (a, b) {
return SortByProps(a, b, { "name": "ascending", "age": "descending" });
});
console.log(items)
})();
(function desc(){
items.sort(function (a, b) {
return SortByProps(a, b, { "name": "descending", "age": "descending" });
});
console.log(items)
})();
(function default(){
items.sort(function (a, b) {
return SortByProps(a, b);
});
console.log(items)
})();
function SortByProps(item1, item2, obj) {
var props = [];
if(obj){
props.push(obj)
}
var cps = [];
var asc = true;
if (props.length < 1) {
for (var p in item1) {
if (item1[p] > item2[p]) {
cps.push(1);
break;
} else if (item1[p] === item2[p]) {
cps.push(0);
} else {
cps.push(-1);
break;
}
}
}
else {
for (var i = 0; i < props.length; i++) {
var prop = props[i];
for (var o in prop) {
asc = prop[o] === "ascending";
if (item1[o] > item2[o]) {
cps.push(asc ? 1 : -1);
break;
} else if (item1[o] === item2[o]) {
cps.push(0);
} else {
cps.push(asc ? -1 : 1);
break;
}
}
}
}
for (var j = 0; j < cps.length; j++) {
if (cps[j] === 1 || cps[j] === -1) {
return cps[j];
}
}
return false;
}