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
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:
maybe not what you’re looking for, but you can use an npm package
https://www.npmjs.com/package/sort-international