To sort mixed alpha/numeric array with JavaScript, we use the localeCompare
method.
For instance, we write
const sortAlphaNum = (a, b) => a.localeCompare(b, "en", { numeric: true });
const arr = [
"A1",
"A10",
"A11",
"A12",
"A2",
"A3",
"A4",
"B10",
"B2",
"F1",
"F12",
"F3",
];
const sorted = arr.sort(sortAlphaNum);
to define the sortAlphaNum
function that returns the result of localeCompare
to compare a
and b
.
We set numeric
to true
compare numeric values.
Then we call arr.sort
with sortAlphaNum
to return an array with the values in arr
sorted.