代码之家  ›  专栏  ›  技术社区  ›  Tales

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

  •  0
  • Tales  · 技术社区  · 1 年前

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

    示例:-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)));
    1 回复  |  直到 1 年前
        1
  •  2
  •   David    1 年前

    因为你不考虑 ascending 决定使用什么时的变量 "-" 价值观

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

    如果您希望根据 提升 ,将其添加到该逻辑中:

    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)));