Sometimes, we want to sort mixed alpha and numeric array with JavaScript.
In this article, we’ll look at how to sort mixed alpha and numeric array with JavaScript.
How to sort mixed alpha and numeric array with JavaScript?
To sort mixed alpha and numeric array with JavaScript, we can use the array sort
and string localeCompare
methods.
For instance, we write
const sortAlphaNum = (a, b) => a.localeCompare(b, "en", { numeric: true });
console.log(
[
"A1",
"A10",
"A11",
"A12",
"A2",
"A3",
"A4",
"B10",
"B2",
"F1",
"F12",
"F3",
].sort(sortAlphaNum)
);
to define the sortAlphaNum
function that calls the localeCompare
method to compare strings a
and b
.
We set numeric
to true
to let us compare numeric strings.
Then we call sort
with sortAlphaNum
to return a new array with the items sorted lexically.
Conclusion
To sort mixed alpha and numeric array with JavaScript, we can use the array sort
and string localeCompare
methods.