做项目有个产品需求;具体是要求根据优先级大小排序一遍,然后根据中文名排一遍,简单说就是二级排序了
var arrayData=[//测试数据 {name:"佛山",priority:2}, {name:"Wish邮_无锡",priority:1}, {name:"腌面",priority:5}, {name:"新加坡",priority:2}, {name:"4PX测试",priority:2}, {name:"a鸡扒",priority:5}, {name:"菜鸟",priority:1}, {name:"台湾",priority:1}, {name:"肉末",priority:5}, {name:"7斤",priority:5}, {name:"6测试",priority:2}, {name:"披萨",priority:5} ]; arrayData.sort(function (a,b) {//优先级排序一遍,因为需要从大排到小所以要reverse反序 return a.priority - b.priority }).reverse(); function chineseSort(array){//中文排序:数字》中文》英文 return array.sort(function compareFunction(index1,index2) { return index1.name.localeCompare(index2.name,"zh"); }); }; var cacheArr=[];//缓存数组 var sortArr=[];//最终排序好的数组
for (var i = 0,arrLen=arrayData.length; i < arrLen; i++) { if (i<arrLen-1) { var thisVal = arrayData[i].priority; var nextVal = arrayData[i+1].priority; if (thisVal==nextVal) { cacheArr.push(arrayData[i]) }else{ cacheArr.push(arrayData[i]) //cacheArr本身就是一个数组不能直接push添加,而要apply融合 sortArr.push.apply(sortArr,chineseSort(cacheArr)) cacheArr=[];//清空缓存数组 } }else{ cacheArr.push(arrayData[i]) sortArr.push.apply(sortArr,chineseSort(cacheArr)) } } console.log(sortArr)//结果