前台:多个对象依次排序
/**
*
- @param {*} itema 第一元素
- @param {*} itemb 第二元素
- @param {*} keyList sortKey list(key的顺序值)[“id”,“name”,“age”]
- @param {*} keyIdx 当前sortkey
- @param {*} sortKeyList 排序(升序 降序) [“desc”, “asc”, “asc”]
*/
var keyList = [‘age’,‘name’,‘id’];
var sortKeyList = [‘asc’,‘asc’,‘asc’];
var keyIdx = 0;
var sortKey = ‘’;
dataList.sort(function(itema,itemb){
return compare(itema, itemb, keyList, keyIdx, sortKeyList);
});
function compare(itema, itemb, keyList, keyIdx, sortKeyList){
let key = keyList[keyIdx];
if (itema[key]< itemb[key]){
return getSortResult(sortKeyList[keyIdx]);
}else if (itema[key]> itemb[key]) {
return getSortResult(sortKeyList[keyIdx]) * -1;
} else {
keyIdx++;
if (keyIdx === keyList.length){
return 0;
}
return compare(itema, itemb, keyList, keyIdx, sortKeyList);
}
}
function getSortResult(sortKey){
if (sortKey === ‘asc’) {
return -1;
}else {
return 1;
}
}
// 输出结果
console.log(dataList);
// 数据
var dataList=[
{id:1, name:“taro”, age:10},
{id:3, name:“yuki”, age:20},
{id:4, name:“akane”, age:20},
{id:2, name:“akane”, age:20},
{id:5, name:“takasi”, age:27},
{id:6, name:“kaori”, age:32}
];