Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting Hungarian dictionary

I'm trying to sort Hungarian words in the dictionary by alphabetical order. The expected order for all letters should be aábcdeéfggyhiíjklmnoóöőpqrsttyuúüűvwxyz

I was trying to use Intl.Collator() and localeCompare but the expected output was never right.

for example:

console.log(["baj", 'betűz', 'ä', "bácsi"].sort(new Intl.Collator('hu').compare));
//expected output ["ä", "baj", "bácsi", "betűz"]

what I got is Array ["ä", "bácsi", "baj", "betűz"]

á comes before a but should be after a

and it happened for é and í also.

I was trying to use

.sort(function(a, b) {
  let letterA = a.toUpperCase();
  let letterB = b.toUpperCase();
  if (letterA < letterB) {
    return -1;
  }
  if (letterA > letterB) {
    return 1;
  }
  return 0;
});

but words with specials signs were put at the end of the array which is not what I want.

Any suggestions on how can I resolve that issue?

like image 625
Daniel Wiśniewski Avatar asked Jan 20 '26 16:01

Daniel Wiśniewski


1 Answers

You could sort by hand and get the wanted order with a given alphabet.

const
    alphabet = 'aábcdeéfggyhiíjklmnoóöőpqrsttyuúüűvwxyz',
    order = Object.fromEntries([].map((c, i) => [c, i + 1])),
    compare = (a, b) => {
        let i = 0,
            l = Math.min(a.length, b.length),
            r = 0;
            
        while (!r && i < l) {
            r = a[i] in order && b[i] in order ? order[a[i]] - order[b[i]] : a[i].localeCompare(b[i]);
            i++;
        }
        return r || a.length - b.length;
    }

console.log(...["baj", 'betűz', 'ä', "bácsi"].sort(compare)); // ["ä", "baj", "bácsi", "betűz"]
like image 123
Nina Scholz Avatar answered Jan 22 '26 04:01

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!