Sorting a string array with uppercase first including accents
You can simply extend the sort function to prioritize uppercase characters in the beginning of strings:
const arr = ['ÁRBOL', 'único', 'UNICO', 'árbol', 'ARBOL', 'cosas', 'COSAS', 'fútbol', 'FUTBOL'];
function startsWithUppercase(str) {
return str.substr(0, 1).match(/[A-Z\u00C0-\u00DC]/);
}
arr.sort(function(a, b) {
if (startsWithUppercase(a) && !startsWithUppercase(b)) {
return -1;
} else if (startsWithUppercase(b) && !startsWithUppercase(a)) {
return 1;
}
return a.localeCompare(b);
});
console.log(arr);
I don't believe it's possible with localeCompare
alone, see:
How to get localeCompare to behave similarly to .sort(), so that all capital letters come first?:
But you can combine the method described here with sort
:
const arr = ['único', 'UNICO', 'árbol', 'ARBOL', 'cosas', 'COSAS', 'fútbol', 'FUTBOL'];
const norm = str => str.normalize('NFD').replace(/[\u0300-\u036f]/g, "")
arr.sort((a, b) => Number(norm(a) > norm(b)) || -(Number(norm(b) > norm(a))));
console.log(arr);
// ['ARBOL', 'COSAS', FUTBOL', 'UNICO', 'árbol', 'cosas', 'fútbol', 'único']