记录一个排序方法,方便以后可以直接用了,不用再写了
/**
* 对数组排序
* @param {Array} sortData 排序数据
* @param {String} firstKey 第一排序键
* @param {Boolean} firstAsc 默认:降序 true-升序
* @param {String} secondKey 第二排序键
* @param {Boolean} secondAsc 默认:降序 true-升序
* @param {String} thirdKey 第三排序键
* @param {Boolean} thirdAsc 默认:降序 true-升序
*
*/
sameSortFunc = function (sortData, [firstKey,firstAsc=false], [secondKey, secondAsc=false], [thirdKey, thirdAsc=false]) {
sortData.sort((a,b)=>{
if(a[firstKey] !== b[firstKey]){
if (firstAsc){
return a[firstKey] - b[firstKey];
}
return b[firstKey] - a[firstKey];
}
if(a[secondKey] !== b[secondKey]){
if (secondAsc) {
return a[secondKey] - b[secondKey];
}
return b[secondKey] - a[secondKey];
}
if (thirdAsc){
return a[thirdKey] - b[thirdKey];
}
return b[thirdKey] - a[thirdKey];
});
};
使用方法:
let sortArr = [
{
key1: 111,
key2: 112,
key3: 113,
},
{
key1: 121,
key2: 122,
key3: 133,
},
]
// 全部降序
sameSortFunc(sortArr, ['key1'], ['key2'], ['key3']);
// 第一个升序
sameSortFunc(sortArr, ['key1', true], ['key2'], ['key3']);
// 第三个升序
sameSortFunc(sortArr, ['key1'], ['key2'], ['key3', true]);
// 全部升序
sameSortFunc(sortArr, ['key1', true], ['key2', true], ['key3', true]);