js中文汉字按拼音排序
代码1,拼音排序:
var array = ['武汉', '北京', '上海', '天津']; var resultArray = array.sort( function compareFunction(param1, param2) { return param1.localeCompare(param2,"zh"); } ); console.log(resultArray);
火狐浏览器 resultArray 结果为:[ '北京' , '上海' , '天津' ,'武汉' ] ;
代码2,拼音排序并按字母分类:
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工具库