如何将特定值“-”在升序排序时排在底部,在降序排序时排在顶部?

问题描述 投票:0回答:1

我想按升序和降序对数组进行排序,当数组按升序排序时,我还希望在底部有一个特定的“-”值,并且当按升序排序时,希望相同的值位于数组的顶部降序排列。

示例:- 数组:["-", "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)));

javascript sorting
1个回答
0
投票

因为在决定如何处理

ascending
值时,您没有考虑
"-"
变量:

if (a === "-") {
    return -1;
}
if (b === "-") {
    return 1;
}

如果您希望结果根据

ascending
进行更改,请将其添加到该逻辑中:

function alphabetically(ascending) {
  return function (a, b) {
    // equal items sort equally
    if (a === b) {
        return 0;
    }

    // nulls sort after anything else
    if (a === "-") {
        return ascending ? 1 : -1;
    }
    if (b === "-") {
        return ascending ? -1 : 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)));

© www.soinside.com 2019 - 2024. All rights reserved.