skip to Main Content

Sorting words(Hungarian words with Hungarian accents) in an array.

How to reach the following sort order: [ 'ab', 'abbb', 'áb' ]
From the following source: ['áb', 'ab', 'abbb'] with sort in JavaScript?

Which is the best so simplest and shortest way of that than the following code?

const hunCharsOrder = 'aábcdeéfggyhiíjklmnoóöőpqrsttyuúüűvwxyz';
const order = new Map([... hunCharsOrder].map((c, i) => [c, i + 1]));

const comparator = (a, b) => {
    const minLength = a.length < b.length ? a.length : b.length;

    for (let i = 0; i < minLength; i++) {
        const diff = (order.get(a[i]) || 0) - (order.get(b[i]) || 0);
        if (diff !== 0) return diff;
    }
    return a.length - b.length;
};

2

Answers


  1. Yes, you can achieve the correct sorting order by using the built-in localeCompare() method in JavaScript, which respects language-specific sorting rules, including accented characters like á.

    Here’s how you can do it in the simplest and most reliable way:

    const words = ["áb", "ab", "abbb"];
    
    const sortedWords = words.sort((a, b) => a.localeCompare(b, "hu"));
    
    console.log(sortedWords); // Output: ['ab', 'abbb', 'áb']
    
    Login or Signup to reply.
  2. maybe not what you’re looking for, but you can use an npm package

    https://www.npmjs.com/package/sort-international

    $ npm install sort-international
    
    const international = require('sort-international');
    console.log([ 'áb', 'ab', 'abbb' ].toSorted(international()); // [ 'ab', 'abbb', 'áb' ]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search