简体   繁体   English

JavaScript Array.sort() 在 Firefox 中不起作用

[英]JavaScript Array.sort() not working in Firefox

say I have an array that I want to sort, that a certain element will be first, and leave the rest the way it is.假设我有一个要排序的数组,某个元素将排在第一位,然后将 rest 保持原样。

for example [1,2,3,4] and I want the 2 to be at the beginning of the array例如 [1,2,3,4] 我希望 2 位于数组的开头

[1,2,3,4].sort((a,b)=> a == 2 ? -1 : 0)

in chrome the output is as expected在 chrome 中 output 符合预期

// chrome
[2,1,3,4]

but in Firefox the output is different and the 2 is not first但在 Firefox 中,output 不同,2 不是第一个

// firefox
[1,2,3,4]

You also need to handle the cases were b is 2 properly:您还需要正确处理b2的情况:

 .sort((a, b) => (b === 2) - (a === 2))

but in Firefox the array is not sorted但在 Firefox 中,数组未排序

Not quite, Firefox might use a different sorting algorithm, such that the sorter is called with different arguments in a different order.不完全是,Firefox 可能使用不同的排序算法,这样排序器会以不同的顺序使用不同的 arguments 调用。 The array is only sorted correctly in all different implementations if the following conditions are always true:如果以下条件始终为真,则数组仅在所有不同的实现中正确排序:

  sorter(a, a) === 0
  sorter(a, b) === - sorter(b, a)

Note that sorting is usually O(n log n) average case (though it could be better if a lot of elements are equal), whereas the problem can be solved in O(n):请注意,排序通常是 O(n log n) 的平均情况(尽管如果很多元素相等可能会更好),而问题可以在 O(n) 中解决:

 const withoutTwo = array.filter(it => it !== 2);
 const result =
   Array.from({ length: array.length - withoutTwo.length }).fill(2)
    .concat(withoutTwo);
[1,2,3,4].sort((a,b)=> a == 2 ? -1 : (b==2 ? 1 :0))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM