1.数字排序
var att = [14,25,1,98,57,6,98];
att.sort((a,b)=>{
return a - b;
})
console.log(att);//[1, 6, 14, 25, 57, 98, 98]
2.纯汉字排序
var att1 = ['武汉', '北京', '上海', '天津'];
att1.sort (
function compareFunction(param1, param2) {
return param1.localeCompare(param2,"zh");
}
);
console.log(att1);//["北京", "上海", "天津", "武汉"]
3.纯字母
var arr2 = ["ssdas","asd","sfdf","bsad","psi"];
arr2.sort (function(a,b){return a.localeCompare(b)});
console.log(arr2);//["asd", "bsad", "psi", "sfdf", "ssdas"]
4.字母+汉字(先把汉字排完在排字母)
var arr3 = ["a水电费","b是蒋介石的",'武汉', '北京',"asds",'上海', '天津',"啊行行行","是的","cs是否","b阿斯蒂芬"];
arr3.sort (
function compareFunction(param1, param2) {
return param1.localeCompare(param2,"zh");
}
);
console.log(arr3);//["啊行行行", "北京", "上海", "是的", "天津", "武汉", "a水电费", "asds", "b阿斯蒂芬", "b是蒋介石的", "cs是否"]
5.汉字+字母(先汉字后字母)
思路:先把汉字转化为拼音然后排序,汉字转化拼音的插件 pinyin.js,引入pinyin.js
下载链接: https://pan.baidu.com/s/1GAfgq8tIzLPcUX8NQoDreA 提取码: i8tz
var arr4 =["a北京","b啊蒋介石的",'武汉', '北京', '暧昧', '天津',"a行行行","是的","cs是否","b阿斯蒂芬","陛下","啊破"];
var resultArray = arr4.sort(
function compareFunction(param1, param2) {
return param1.localeCompare(param2,"zh");
}
);
resultArray = resultArray.sort(
function compareFunction(param1, param2) {
return CC2PY(param1).toLowerCase().trim().split("")[0].localeCompare(CC2PY(param2).toLowerCase().trim().split("")[0],"zh");
}
);
console.log(resultArray);//["啊破", "暧昧", "a北京", "a行行行", "北京", "陛下", "b是蒋介石的", "b阿斯蒂芬", "cs是否", "是的", "天津", "武汉"]