最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sort array in Czech, localeCompare - Stack Overflow

programmeradmin6浏览0评论

I have problem sorting an array with Czech names. It works ok for the normal characters but not for the special ones. 'Sb', 'St', 'Šk' ; the special Š should be after the other two words, but it end it up in different order. Here is a simple code.

var tmpArr = ['Sb', 'BE', 'De', 'CS', 'Au', 'Šk', 'De', 'St', 'Ci', 'št'];

function mySort(s1, s2) {
return s1.localeCompare(s2 ,'cz', {sensitivity: "variant"});
}

var sorted = tmpArr.sort(mySort);

console.log(tmpArr);

for(var i in sorted){
console.log(sorted[i]);
}

This should be also working in all browsers.

I have problem sorting an array with Czech names. It works ok for the normal characters but not for the special ones. 'Sb', 'St', 'Šk' ; the special Š should be after the other two words, but it end it up in different order. Here is a simple code.

var tmpArr = ['Sb', 'BE', 'De', 'CS', 'Au', 'Šk', 'De', 'St', 'Ci', 'št'];

function mySort(s1, s2) {
return s1.localeCompare(s2 ,'cz', {sensitivity: "variant"});
}

var sorted = tmpArr.sort(mySort);

console.log(tmpArr);

for(var i in sorted){
console.log(sorted[i]);
}

This should be also working in all browsers.

Share Improve this question edited Jul 16, 2013 at 13:39 sla55er asked Jul 9, 2013 at 7:08 sla55ersla55er 8111 gold badge11 silver badges17 bronze badges 1
  • 2 developer.mozilla/en-US/docs/Web/JavaScript/Reference/… – Karoly Horvath Commented Jul 9, 2013 at 7:17
Add a ment  | 

1 Answer 1

Reset to default 9

Dobrý Den,

as this states

https://developer.mozilla/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/localeCompare

advanced options for locale pare are not implemented in mon browsers.

If you need this only for Chech language maybe it would be best idea to implement your own string parison using characters map:

var charMapL = " 0123456789aábcčdďeéěfghiíjklmnňoópqrřsštťuúůvwxyýzž";
var charMapU = " 0123456789AÁBCČDĎEÉĚFGHIÍJKLMNŇOÓPQRŘSŠTŤUÚŮVWXYÝZŽ";
var charsOrder = {};
for(var i in charMapL.split('')) {
    charsOrder[charMapL[i]] = parseInt(i);
    charsOrder[charMapU[i]] = parseInt(i);
}

function mySort(s1, s2) {
    var idx = 0;
    while ( (idx < s1.length) && (idx < s2.length) && (charsOrder[s1[idx]] == charsOrder[s2[idx]])) {
        idx ++;
    }
    if ((idx == s1.length) && (idx == s2.length)) return 0;
    if (idx == s1.length) return 1;
    if (idx == s2.length) return -1;
    return charsOrder[s1[idx]] > charsOrder[s2[idx]] ? 1 : (charsOrder[s1[idx]] < charsOrder[s2[idx]] ? -1 : 0);
}

console.log(tmpArr);
tmpArr.sort();
console.log(tmpArr);
tmpArr.sort(mySort);
console.log(tmpArr);

http://jsfiddle/GNNBc/1/

发布评论

评论列表(0)

  1. 暂无评论