我知道我可以通过创建嵌套数组以更实用的方式对数组进行排序:
[ [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 :
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/