How can we do alphanumeric sorting in typescript to get the following series? ['1_11', '1_10', '1_9'...'1_1','1_0']
Should it be split and sorted separately?
How can we do alphanumeric sorting in typescript to get the following series? ['1_11', '1_10', '1_9'...'1_1','1_0']
Should it be split and sorted separately?
If you want full control over the sort order of the delimited values, you'll not be able to avoid splitting the values first. The solution below uses the compare2By() higher-order function to let you choose the sort key order and ascending/descending ordering per key.
(UPDATED to support key specific sort orders)
type Comparator<T> = (a: T, b: T) => number;
function compareAsc<T>(a: T, b: T) {
return a < b ? -1 : a > b ? 1 : 0;
}
function compareDesc<T>(a: T, b: T) {
return a < b ? 1 : a > b ? -1 : 0;
}
function compare2By<T extends any[]>(
x = 0,
y = 1,
cmpX: Comparator<T[0]> = compareAsc,
cmpY: Comparator<T[1]> = compareAsc
) {
return (a: T, b: T) =>
cmpX(a[x], b[x]) || cmpY(a[y], b[y]);
}
function sortDelimited(src: string[], sortFn: Comparator<number[]>, del = "_") {
return src
.map((x) => x.split(del))
// optional int coercion, not sure if needed for OP
.map((x) => x.map((y) => parseInt(y)))
.sort(sortFn)
.map((x) => x.join(del));
}
console.log(
JSON.stringify(sortDelimited(
['1_11', '1_10', '1_9', '1_1', '1_0'],
// UPDATED: use total descending order
// for both first and second sort key
compare2By(0, 1, compareDesc, compareDesc)
))
)
// ["1_11","1_10","1_9","1_1","1_0"]
this will sort the array:
this.array = this.array.sort((a, b) => {
return +a.replace('_', '') > +b.replace('_', '') ? -1 : a === b ? 0 : 1
})