默认asc正序,desc倒序。
主要代码:
function SortObjectQuick(sourceObjArr,keyObj,sortType="asc"){
try{
for(let i=0,length=sourceObjArr.length;i<length;i++){
if(Object.isSealed(sourceObjArr[i])&&typeof sourceObjArr[i]==Object){
throw new Error("Error!The object have been sealed.Arr index:"+i+"!")
}
if(Object.isFrozen(sourceObjArr[i])&&typeof sourceObjArr[i]==Object){
throw new error("Error!The object have been Freeze.Arr index:"+i+"!")
}
/*
if(Object.isExtensible(sourceObjArr[i])){
throw new error("Error!The object have been PreventExtensions.Arr index:"+i+"!")
}
*/
}
return sortQuick(sourceObjArr,keyObj,sortType);
}catch(err){
let msg="错误信息:";
msg+=err.message;
console.log(msg)
}
}
function sortQuick(sourceObjArr,keyObj,sortType){
if(sourceObjArr.length<=1)
return sourceObjArr;
let leftArr=new Array(),
rightArr=new Array();
let privotIndex=Math.floor(sourceObjArr.length/2);
let privotVal=sourceObjArr[privotIndex];
sourceObjArr.forEach((item,index)=>{
if(index!==privotIndex){
if(typeof keyObj=="string"){//对象数组
if(sortType=="asc"){
if(item[keyObj]<privotVal[keyObj]){
leftArr.push(item);
} else{
rightArr.push(item);
}
}else if(sortType=="desc"){
if(item[keyObj]>privotVal[keyObj]){
leftArr.push(item);
} else{
rightArr.push(item);
}
}
}else{//数值数组
if(sortType=="asc"){
if(item<privotVal){
leftArr.push(item);
} else{
rightArr.push(item);
}
}else if(sortType=="desc"){
if(item>privotVal){
leftArr.push(item);
} else{
rightArr.push(item);
}
}
}
}
})
return sortQuick(leftArr,keyObj,sortType).concat([privotVal],sortQuick(rightArr,keyObj,sortType));
}
测试:
let data=[
{
id:2,
name:"zhang"
},
{
id:1,
name:"li"
},
{
id:2,
name:"wu"
},
{
id:3,
name:"go"
}
]
let data1=[12,124,3,432,23,324,234,234,452,67,43];
console.log(SortObjectQuick(data,"id"))
console.log(SortObjectQuick(data1,null))
输出结果:

来源:CSDN
作者:Lpd_Reason
链接:https://blog.csdn.net/qq_40283784/article/details/103873393