Sunday, December 28, 2014

Simple JavaScript function to compare and sort localized strings

A recurring problem in JavaScript is sorting localized strings, that is, strings having characters from outside of the ASCII [A-Za-z] range, like for example the Spanish characters áéíóúüñ (and their uppercase equivalents).

For this problem I wrote the JavaScript function getLocaleStrCmpFn, which returns a function to compare and sort strings depending on the order given as parameter, for example, to sort an array of strings having Spanish characters you can do:

var ordES = ['AaÁá','Bb','Cc','Dd','EeÉé','Ff','Gg','Hh',
'IiÍí','Jj','Kk','Ll','Mm','Nn','Ññ','OoÓó','Pp','Qq',
'Rr','Ss','Tt','UuÚúÜü','Vv','Ww','Xx','Yy','Zz'];
var fnES = getLocaleStrCmpFn(ordES);

var arr = ['Álamo','abedul','Arce','abeto','Castaño','acacia'];
arr.sort(fnES);

Other ways to do it are the localeCompare function with additional non-standard arguments or the future JavaScript Internationalization API, but both are not supported in many versions of major browsers, so the locale-str-cmp.js solution is an easy way to sort strings for a specific locale or to create custom comparison functions. What do you think?

No comments:

Post a Comment