【发布时间】:2021-11-28 04:15:14
【问题描述】:
我有一个这样的数组
["1","0K","11",1,"KE","PQ",5,"5"]
我希望它首先按文本排序,然后按如下数字排序
["KE","PQ","0K","1",1,5,"5","11"]
我使用了local compare,但它似乎不起作用。
function desc(a,b){
//below is the code that needs improvement
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")))
【问题讨论】:
-
为什么是
"KE","PQ","0K"?字符串比较将给出"0K","KE","PQ"或相反的结果。 -
你的OK是Kay的零。 0K。将所有内容转换为字符串并使用 array.sort().reverse()
-
i want it to sort first by text带有零的文本"KE","PQ","0K"永远不会按该顺序排序。它将是"0K","KE","PQ"或相反的顺序。 -
你想如何比较字母的?因为使用
localeCompare在KE之前设置PQ
标签: javascript arrays sorting alphanumeric