我想按升序和降序对数组进行排序,当数组按升序排序时,我希望在底部有一个特定的“-”值,而当数组按降序排序时,也希望在数组的顶部有相同的值。
示例:-array:[“-”,“a”,“z”,“-”和“b”],升序:[“a”、“b”、“z”、“-”、“–”],降序:[“-“、”-“、z、”b“、”a“]
我尝试过下面的代码,但“-”始终位于顶部。请帮忙找出我在这里犯了什么错误。提前感谢!
function alphabetically(ascending) {
return function (a, b) {
// equal items sort equally
if (a === b) {
return 0;
}
// nulls sort after anything else
if (a === "-") {
return -1;
}
if (b === "-") {
return 1;
}
// otherwise, if we're ascending, lowest sorts first
if (ascending) {
return a < b ? -1 : 1;
}
// if descending, highest sorts first
return a < b ? 1 : -1;
};
}
var arr = ["-", "a", "z", "-", "b"];
console.log(arr.sort(alphabetically(true)));
console.log(arr.sort(alphabetically(false)));