【问题标题】:How to sort an array with duplicate values using Array.prototype.sort()?如何使用 Array.prototype.sort() 对具有重复值的数组进行排序?
【发布时间】:2019-09-20 12:51:02
【问题描述】:

我想使用Array.prototype.sort() 对具有重复值的数组进行排序。

例如,如果我执行此[1, 2, 0, 1].sort((a, b) => a + b) 以实现按降序排列的数组,我将返回相同的数组[1, 2, 0, 1]

为什么会发生这种情况,如何使用Array.prototype.sort 对该数组进行排序? javascript 的数组排序对于通过重复值进行排序是不可靠的,还是我提供的函数没有进行正确的比较?我想使用Array.prototype.sort 来实现这一点,而不必编写自己的排序函数。

谢谢!

【问题讨论】:

  • .sort((a, b) => a - b) 也许。而sort 不会返回新数组。它会改变现有的数组。

标签: javascript arrays sorting duplicates


【解决方案1】:

你需要减去这两个值。

//ascending order
console.log([1, 2, 0, 1].sort((a, b) => a - b))

//descending order
console.log([1, 2, 0, 1].sort((a, b) => b - a))

【讨论】:

    【解决方案2】:

    它不起作用的原因是:

    如果你查看offical MDN Documentation

    sort() 方法对数组的元素进行就地排序并返回 数组。默认排序顺序是建立在转换 元素转换成字符串,然后对数组进行比较。

    var months = ['March', 'Jan', 'Feb', 'Dec'];
    months.sort();
    console.log(months);
    // expected output: Array ["Dec", "Feb", "Jan", "March"]
    
    var array1 = [1, 2, 0, 1];
    array1.sort((a, b) => a + b);
    console.log(array1);
    // expected output: Array [1, 2, 0 ,1]

    所以,要比较数字而不是字符串,比较函数可以 只需从 a 中减去 b。以下函数将对数组进行排序 升序(如果它不包含 Infinity 和 NaN)

    function compareNumbers(a, b) {
      return a - b;
    }

    【讨论】:

      猜你喜欢
      • 2021-12-20
      • 1970-01-01
      • 2017-04-12
      • 2021-08-22
      • 1970-01-01
      • 2021-08-26
      • 2021-02-15
      • 2013-01-08
      • 2012-09-26
      相关资源
      最近更新 更多