js中文漢字按拼音排序

代碼1,拼音排序:git

var array = ['武漢', '北京', '上海', '天津'];
var resultArray = array.sort(
    function compareFunction(param1, param2) {
        return param1.localeCompare(param2,"zh");
    }
);
console.log(resultArray);

火狐瀏覽器 resultArray 結果爲:[ '北京' , '上海' , '天津' ,'武漢' ] ;github

 

代碼2,拼音排序並按字母分類:web

 1 function pySegSort(arr,empty) {
 2     if(!String.prototype.localeCompare)
 3         return null;
 4      
 5     var letters = "*abcdefghjklmnopqrstwxyz".split('');
 6     var zh = "阿八嚓噠妸發旮哈譏咔垃痳拏噢妑七呥扨它穵夕丫帀".split('');
 7      
 8     var segs = [];
 9     var curr;
10     $.each(letters, function(i){
11         curr = {letter: this, data:[]};
12         $.each(arr, function() {
13             if((!zh[i-1] || zh[i-1].localeCompare(this,"zh") <= 0) && this.localeCompare(zh[i],"zh") == -1) {
14                 curr.data.push(this);
15             }
16         });
17         if(empty || curr.data.length) {
18             segs.push(curr);
19             curr.data.sort(function(a,b){
20                 return a.localeCompare(b,"zh");
21             });
22         }
23     });
24     return segs;
25 }

 

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.jb51.net/article/100864.htm      ----------JS實現超簡單的漢字轉拼音功能示例
           https://github.com/sxei/pinyinjs                  -----------一個實現漢字與拼音互轉的小巧web工具庫
相關文章
相關標籤/搜索