码迷,mamicode.com
首页 > 编程语言 > 详细

js中文汉字按拼音排序

时间:2016-07-11 00:59:35      阅读:367      评论:0      收藏:0      [点我收藏+]

标签:

代码1,拼音排序:

var array = [‘武汉‘, ‘北京‘, ‘上海‘, ‘天津‘];
array = array.sort(
    function compareFunction(param1, param2) {
        return param1.localeCompare(param2);
    }
);
console.log(resultValue);

array结果为:[ ‘北京‘ , ‘上海‘ , ‘天津‘ ,‘武汉‘ ] ;

 

代码2,拼音排序并按字母分类:

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":["",""]}
]"
 
 
扩展:http://blog.csdn.net/testcs_dn/article/details/25116655

js中文汉字按拼音排序

标签:

原文地址:http://www.cnblogs.com/wteng/p/5658972.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!