js数组sort排序规则
实现一个数组排序函数 对数组[ “A华北”, “A华南”,“B华南”,“A华东”,“B华东”,“A华西”, “C华北”,“A华东” ]; 排序为[‘A华东’, ‘A华东’, ‘A华南’, ‘A华西’, ‘A华北’, ‘B华东’, ‘B华南’, ‘C华北’] 排序规则为相同字母A-C开头的A在前面,B、C次之;A相同的情况下按照东南西北排序
function sort(arr) {
const ABCarr = ["A", "B", "C"];
const strArr = ["东", "南", "西", "北"];
const newArr = arr.sort((a, b) => {
let tmpa = ABCarr.indexOf(a.slice(0, 1));
let tmpb = ABCarr.indexOf(b.slice(0, 1));
if(tmpa===tmpb){
tmpa = strArr.indexOf(a.slice(2));
tmpb = strArr.indexOf(b.slice(2));
return tmpa - tmpb;
}
});
return newArr
}
let arr=["A华北", "A华南","B华南","A华东","B华东","A华西", "C华北","A华东" ];
console.log(sort(arr));
|