[JavaScript] Is it possible to sort mixed numbers, accented, non-accented and uppercase letters?
For example, taken from another programming forum, I replaced [^a-zA-Z]
for [^a-z\u00E0-\u00FC]
:
var reA = /[^a-z\u00E0-\u00FC]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b)
{
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA)
{
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
}
else
{
return aA > bA ? 1 : -1;
}
}
console.log(
["3", "2", "10", "40", "6", "4", "30", "33", "1", "Gustavo", "julho", "Klaus", "Ιαπωνία", "keyboard", "სკოლა", "último", "árbol", "γυναίκα", "uma", "água", "Argentina", "Ángelo", "argelino", "unido", "женщина", "κήπος", "друг", "дом", "ბაღი", "люди", ].sort(sortAlphaNum)
)
I also added Intl.Collator().compare
, beocming sort(sortAlphaNum)
into sort(Intl.Collator(sortAlphaNum).compare)
, but the numbers, accented, non-accented and uppercase are in the wrong order.
- Without
Intl.Collator().compare
, the numbers order is correct, but the alphabetical order of non-accented, accented and upper letters is incorrect. See the output:
0: "1"
1: "2"
2: "3"
3: "4"
4: "6"
5: "10"
6: "30"
7: "33"
8: "40"
9: "Ιαπωνία"
10: "სკოლა"
11: "γυναίκα"
12: "женщина"
13: "κήπος"
14: "друг"
15: "дом"
16: "ბაღი"
17: "люди"
18: "argelino"
19: "julho"
20: "keyboard"
21: "Klaus"
22: "Ángelo"
23: "Argentina"
24: "uma"
25: "unido"
26: "Gustavo"
27: "água"
28: "árbol"
29: "último"
- With
Intl.Collator().compare
, the numbers order is incorrect, but the alphabetical order of non-accented, accented and upper letters is correct. See the output:
0: "1"
1: "10"
2: "2"
3: "3"
4: "30"
5: "33"
6: "4"
7: "40"
8: "6"
9: "água"
10: "Ángelo"
11: "árbol"
12: "argelino"
13: "Argentina"
14: "Gustavo"
15: "julho"
16: "keyboard"
17: "Klaus"
18: "último"
19: "uma"
20: "unido"
21: "γυναίκα"
22: "Ιαπωνία"
23: "κήπος"
24: "дом"
25: "друг"
26: "женщина"
27: "люди"
28: "ბაღი"
29: "სკოლა"