Home > Web Front-end > JS Tutorial > JS method to sort Chinese characters by pinyin

JS method to sort Chinese characters by pinyin

小云云
Release: 2018-01-26 16:30:06
Original
4566 people have browsed it

This article mainly introduces the method of JS to sort Chinese characters by pinyin, involving JavaScript conversion, traversal, sorting and other related operation skills for Chinese strings. Friends who need it can refer to it. I hope it can help everyone.

Code 1, Pinyin sorting:


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

Firefox resultArray The result is:


[ '北京' , '上海' , '天津' ,'武汉' ] ;
Copy after login

Code 2, sorted by pinyin and sorted alphabetically:


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,"zh") <= 0) && this.localeCompare(zh[i],"zh") == -1) {
    curr.data.push(this);
   }
  });
  if(empty || curr.data.length) {
   segs.push(curr);
   curr.data.sort(function(a,b){
    return a.localeCompare(b,"zh");
   });
  }
 });
 return segs;
}
JSON.stringify(pySegSort(["我","不","懂","爱","啊","按","已","呀","选","县"]))
Copy after login

Result:


"[
  {"letter":"a","data":["啊","爱","按"]},
  {"letter":"b","data":["不"]},
  {"letter":"d","data":["懂"]},
  {"letter":"w","data":["我"]},
  {"letter":"x","data":["县","选"]},
  {"letter":"y","data":["呀","已"]}
]"
Copy after login

Related recommendations:

About Chinese pinyin sorting

mysql Chinese pinyin sorting implementation method

JavaScript method to implement pinyin sorting_javascript skills

The above is the detailed content of JS method to sort Chinese characters by pinyin. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template