js Chinese characters are sorted by pinyin

JavaScript provides localized text sorting, such as sorting Chinese according to pinyin, without the need for programs to display and compare the pinyin of strings.

String.prototype.localeCompare Under the premise of not considering polyphonic words, the sorting according to pinyin can basically be perfectly realized.

Every browser that supports localeCompare works fine, without exception. Recently updated Chrome to 58.0.3029.110, and suddenly found that the Chinese sorting is not normal.

After confirmation, localeCompare needs to specify the locales parameter explicitly.

 

Code 1, Pinyin sorting:

copy code
var array = ['Wuhan', 'Beijing', 'Shanghai', 'Tianjin'];
var resultArray = array.sort(
    function compareFunction(param1, param2) {
        return param1.localeCompare(param2,"zh");
    }
);
console.log(resultArray);
copy code

Firefox browser resultArray result is: [ 'Beijing' , 'Shanghai' , 'Tianjin' , 'Wuhan' ] ;

 

Code 2, Pinyin sort and alphabetical:

copy code
1 function pySegSort(arr,empty) {
 2     if(!String.prototype.localeCompare)
 3         return null;
 4      
 5     var letters = "*abcdefghjklmnopqrstwxyz".split('');
 6 var zh = "Abahadahahahahahaaaaaaaaaaaaaaaaaaaaaaaaaa".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 }
copy code

 

JSON.stringify(pySegSort([ "我" , "不" , "懂" , "爱" , "啊" , "按" , "已" , "呀" , "选" , "县" ]))
//结果
"[
  {" letter ":" a "," data ":[" "," "," "]} ,
  {" letter ":" b "," data ":[" "]} ,
  {" letter ":" d "," data ":[" "]} ,
  {" letter ":" w "," data ":[" "]},
  {" letter ":" x "," data ":[" "," "]},
  {" letter ":" y "," data ":[" "," "]}
]"
 
 
Extension: http://blog.csdn.net/testcs_dn/article/details/25116655 ------JS gets the first letter of Chinese pinyin, and quickly finds the Chinese content in the page through the first letter of pinyin
           http://www.jb51.net/article/100864.htm ------------ JS implements an example of a super simple function of converting Chinese characters to Pinyin
           https://github.com/sxei/pinyinjs ------------- A small web tool library that realizes the conversion between Chinese characters and pinyin

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325280789&siteId=291194637
Recommended