javascript - 在 JavaScript 中一起使用过滤器和排序方法时排序不正确

标签 javascript arrays sorting

我知道我可以通过创建嵌套数组以更实用的方式对数组进行排序:

                 [ [value,frequency], [value,frequency] ]

并按频率排序。

但是我正在尝试使用另一种方法,因为它在我的脑海中是有意义的,但出于某种原因我无法解释为什么它不能始终如一地工作。

一些测试返回了这些令人费解的结果:

    function arrOrd(arr){
    
    var arr_s=arr.sort(
    
      function(a,b) {
       var u=arr.filter(x=> x==a).length;
       var v=arr.filter(x=> x==b).length;       
       return u-v;    
    })
    
    return arr_s;    
    }

console.log(arrOrd([2,3,5,3,7,9,5,3,7]).toString());  //   ==>[9,2,7,7,5,5,3,3,3]
console.log(arrOrd([4,4,2,5,1,1,3,3,2,8]).toString()); //  ==>[8,5,4,4,2,1,1,3,3,2]
console.log(arrOrd([4,9,5,0,7,3,8,4,9,0]).toString()); //  ==>[8,3,7,5,4,9,0,4,9,0]

我认为这里有一个我没有掌握的新概念,因为我自己似乎无法找到解决方案。一如既往,感谢您的耐心等待和帮助。

最佳答案

排序期间数组的状态是实现定义的。每the spec :

  1. Perform an implementation-dependent sequence of calls to the [[Get]] and [[Set]] internal methods of obj, to the DeletePropertyOrThrow and HasOwnProperty abstract operation with obj as the first argument, and to SortCompare (described below), such that:

    • The property key argument for each call to [[Get]], [[Set]], HasOwnProperty, or DeletePropertyOrThrow is the string representation of a nonnegative integer less than len.
    • The arguments for calls to SortCompare are values returned by a previous call to the [[Get]] internal method, unless the properties accessed by those previous calls did not exist according to HasOwnProperty. If both perspective [sic] arguments to SortCompare correspond to non-existent properties, use +0 instead of calling SortCompare. If only the first perspective argument is non-existent use +1. If only the second perspective argument is non-existent use -1.
    • If obj is not sparse then DeletePropertyOrThrow must not be called.
    • If any [[Set]] call returns false a TypeError exception is thrown.
    • If an abrupt completion is returned from any of these operations, it is immediately returned as the value of this function.

换句话说,对于 JavaScript 引擎,排序的一个完全有效的实现是复制数组,用 "hi" 替换原始数组中的所有元素,然后执行排序复制,并将所有元素替换回来。

如果您对每次比较期间数组的确切状态感到好奇 - 记录下来!

const arr = [5, 2, 3, 1, 4];

arr.sort((a, b) => {
    console.log(arr.join(' '));
    return a - b;
});

在 Firefox 60 中,这总是记录数组的原始状态;在 Chrome 64 中,它记录了几个状态,其中一些具有原始数组不包含的重复元素。

关于javascript - 在 JavaScript 中一起使用过滤器和排序方法时排序不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48966078/

相关文章:

javascript - 在 Winwheel.js 中旋转之前设置要赢得的奖品

javascript - 模块解析失败 : Unexpected token

python - 替代字节数组处理瓶颈的高速替代方案

ios - Swift 4 按第一个值排序字典

javascript - 将 javascript 数组中的重复值分组在一起,然后按值名称升序对这些组进行排序

c - 在C中按升序对链表进行排序

javascript - 如何触发实际由浏览器处理的 KeyboardEvent (DOM_VK_UP),就像用户键入按键一样?

javascript - 在 Highcharts 中添加额外的工具提示

algorithm - 在压缩重复项的序列中找到第 k 个最小的元素?

javascript - 在 MVCarray 中分配纬度和经度