Friday, October 10, 2014

Javascript : Sorting with locale (German Language Sorting)

Javascript's .sort() will work only on English.

So sorting languages like German, French having some special characters in addition to english alphabets is not possible with .sort of javascript.

For array
 var arr = ["Übelkeit", "Veränderte Geschmacksempfindung", "Veränderte Geschmacksempfindung", "Ödem (Schwellung)", "Nasenbluten"] 

normal sorting using

arr.sort(function(a, b) 
     if (typeof a === 'string' && typeof b === 'string')
         return (a > b) ? 1 : ((a < b) ? -1 : 0); }); 

will sort like this.

["Nasenbluten", "Veränderte Geschmacksempfindung", "Veränderte Geschmacksempfindung", "Ödem (Schwellung)", "Übelkeit"] 

But in german Ü = U and the order is Ü < ü < U < u .
also for similar letters.

A small mode to the actual sorting will solve this.
using localeCompare

arr.sort(function(a, b) 
    if (typeof a === 'string' && typeof b === 'string')
        return a.toLowerCase().localeCompare(b.toLowerCase()); 

["Nasenbluten", "Ödem (Schwellung)", "Übelkeit", "Veränderte Geschmacksempfindung", "Veränderte Geschmacksempfindung"]

Happy :) ?