Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array in Czech, localeCompare

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.

like image 824
sla55er Avatar asked Jul 09 '13 07:07

sla55er


1 Answers

Dobrý Den,

as this states

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

advanced options for locale compare are not implemented in common browsers.

If you need this only for Chech language maybe it would be best idea to implement your own string comparison 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.net/GNNBc/1/

like image 148
fsw Avatar answered Oct 12 '22 23:10

fsw