I am trying to make a default sort order on a column that contains a alphanumeric string.
Normal sorting doesn´t work like i want. The result is:
ABC-1-24
ABC-10-24
ABC-2-23
ABC-2-24
What i want is (sort by the last number first, and then the first number):
ABC-2-23
ABC-1-24
ABC-2-24
ABC-10-24
What is the best way to solve this?
I made a function that seems to do the trick, but how do i implement it?
function sortStringsChronologically(strings: string[]): string[] {
return strings.sort((a, b) => {
const partsA = a.split("-");
const partsB = b.split("-");
const midA = parseInt(partsA[1], 10);
const midB = parseInt(partsB[1], 10);
const lastA = parseInt(partsA[2], 10);
const lastB = parseInt(partsB[2], 10);
if(lastA !== lastB) {
return lastA - lastB;
}
if(midA !== midB) {
return midA - midB;
}
return lastA - lastB;
});
}
const strings = ["ABC-1-24", "ABC-1-23", "ABC-3-24", "ABC-10-24", "ABC-2-24"];
const sortedStrings = sortStringsChronologically(strings);
console.log(sortedStrings);
[LOG]: ["ABC-1-23", "ABC-1-24", "ABC-2-24", "ABC-3-24", "ABC-10-24"]