中英文按照首字母A~Z顺序排序

时间:2021-10-08 20:14:07

查了网上很多方法,最后实现如下:(VUE)

数据格式如下:

中英文按照首字母A~Z顺序排序


VUEdata

data: {
filter:{},
brand:[],
},
methods:{

pySort:function(arr,empty){

    var $this = this;
if(!String.prototype.localeCompare)
return null;

var letters ="ABCDEFGHIJKLMNOPQRSTUVWXYZ#".split('');
var zh ="啊把差大额发噶哈*级卡啦吗那哦爬器然撒他**哇西呀咋".split(''); //*占位没有i,u,v拼音开头的汉字

var arrList = [];
for(var m =0;m<arr.length;m++){
arrList.push(arr[m].name);
}

var result = [];
var curr;
for(var i=0;i<letters.length;i++){
curr = {letter: letters[i], data:[]};

if(i!=26){
for(var j =0;j<arrList.length;j++){
var initial = arrList[j].charAt(0); //截取第一个字符
if(arrList[j].charAt(0)==letters[i]||arrList[j].charAt(0)==letters[i].toLowerCase()){ //首字符是英文的
curr.data.push(arrList[j]);
}else if(zh[i]!='*'&&$this.isChinese(initial)){ //判断是否是无汉字,是否是中文
if(initial.localeCompare(zh[i]) >= 0 &&(!zh[i+1]||initial.localeCompare(zh[i+1]) <0)) { //判断中文字符在哪一个类别
curr.data.push(arrList[j]);
}
}
}
}else{
for(var k =0;k<arrList.length;k++){
var ini = arrList[k].charAt(0); //截取第一个字符
if(!$this.isChar(ini)&&!$this.isChinese(ini)){
curr.data.push(arrList[k]);
}
}
}

if(empty || curr.data.length) {
result.push(curr);
curr.data.sort(function(a,b){
return b.localeCompare(a); //排序,英文排序,汉字排在英文后面
});
}
}
return result;
},
isChinese:function(temp){
var re=/[^\u4E00-\u9FA5]/;
if (re.test(temp)){return false ;}
return true ;
},
isChar:function(char){
var reg = /[A-Za-z]/;
if (!reg.test(char)){return false ;}
return true ;
}


最后调用:

$this.filter.brand = [
{name: "AHY", count: 0, selected: 0},{name: "2ITCH'S POUCH", count: 0, selected: 0},{name: "~U.R", count: 0, selected: 0},{name: "bonvivant", count: 0, selected: 0},{name: "dr. jart+", count: 0, selected: 0},{name: "nooni", count: 0, selected: 0},{name: "purplebox", count: 0, selected: 0},{name: "the saem得鲜", count: 0, selected: 0},{name: "农心", count: 0, selected: 0},{name: "可莱丝", count: 0, selected: 0},{name: "太平洋爱茉莉", count: 0, selected: 0},{name: "悦诗风吟", count: 0, selected: 0},{name: "悦诗风吟牌", count: 0, selected: 0},{name: "汤姆农场", count: 0, selected: 0},{name: "海太", count: 0, selected: 0},{name: "美美箱", count: 0, selected: 0},{name: "自然源露", count: 0, selected: 0},{name: "贵爱娘", count: 0, selected: 0}

console.log(JSON.stringify($this.pySort($this.filter.brand)));