My array looks like this
["1","0K","11",1,"KE","PQ",5,"5"]
I need to sort it first by text and then by number as shown below
["KE","PQ","0K","1",1,5,"5","11"]
I attempted using the local compare
method but it was not effective.
function desc(a,b){
//the code below needs improvements
return b.toString().localeCompare(a, undefined, {
numeric: true,
sensitivity: "base",
});
}
function sort(order) {
return order === "desc"
? (a, b) => desc(a, b)
: (a, b) => -desc(a, b);
}
function stableSort(array, cmp){
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = cmp(a[0], b[0]);
if (order !== 0) return order;
return (a[1]) - (b[1]);
});
return stabilizedThis.map((el) => el[0]);
}
var arr = ["1","0K","11",1,"KE","PQ",5,"5"];
console.log(stableSort(arr, sort("asc")))