js拼音排序并按字母分类

js拼音排序并按字母分类,需要String支持localeCompare

ie8,firefox,chrome测试通过
function pySegSort(arr,empty) {
if(!String.prototype.localeCompare)
return null;

var letters ="*abcdefghjklmnopqrstwxyz".split('');
var zh ="啊把差大额发噶哈级卡啦吗那哦爬器然啥他哇西呀咋".split('');

var segs = [];
var curr;
$.each(letters, function(i){
curr = {letter: this, data:[]};
$.each(arr, function() {
if((!zh[i-1] || zh[i-1].localeCompare(this) <= 0) && this.localeCompare(zh[i]) == -1) {
curr.data.push(this);
}
});
if(empty || curr.data.length) {
segs.push(curr);
curr.data.sort(function(a,b){
return a.localeCompare(b);
});
}
});
return segs;
}
JSON.stringify(pySegSort(["我","不","懂","爱","啊","按","已","呀","选","县"]))
//结果
"[{"letter":"a","data":["啊","爱","按"]}
,{"letter":"b","data":["不"]}
,{"letter":"d","data":["懂"]}
,{"letter":"w","data":["我"]}
,{"letter":"x","data":["县","选"]},{"letter":"y","data":["呀","已"]}]"

你可能感兴趣的:(排序,js)