javascriptsorting

Why doesn't localeCompare work as I expect?


I try to sort array data alphabetically but I think something is not OK.

var items;

// it's OK  
items = ['a', 'á'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["a", "á"]

// it's OK, too
items = ['an', 'án'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["an", "án"]

// hmmm, it's not
items = ['an', 'ál'];
items.sort((a, b) => a.localeCompare(b, 'hu'));
console.log(items); // ["ál", "an"]

The Hungarian alphabet starts with a, á, b, c...

Any suggestion, how should I use localecompare function.


Solution

  • In case there is no way to do it with localeCompare it seems as if you have to write your own sorter:

    const alphabet = "aábcdefghijklmnopqrstuvwxyz";
    
    function alphabetically(a, b) {
      a = a.toLowerCase(), b = b.toLowerCase();
      // Find the first position were the strings do not match
      let position = 0;
      while(a[position] === b[position]) {
          // If both are the same don't swap
          if(!a[position] && !b[position]) return 0;
          // Otherwise the shorter one goes first
          if(!a[position]) return 1;
          if(!b[position]) return -1;
          position++;
      }
      // Then sort by the characters position
      return alphabet.indexOf(a[position]) - alphabet.indexOf(b[position]);
    }
    

    Usable as

     array.sort(alphabetically);