JavaScript Array.sort() 在 Firefox 中不工作
JavaScript Array.sort() not working in Firefox
假设我有一个要排序的数组,某个元素排在第一位,其余保持原样。
例如 [1,2,3,4],我希望 2 位于数组的开头
[1,2,3,4].sort((a,b)=> a == 2 ? -1 : 0)
在 chrome 中输出符合预期
// chrome
[2,1,3,4]
但在 Firefox 中输出不同,2 不是第一个
// firefox
[1,2,3,4]
您还需要正确处理 b
是 2
的情况:
.sort((a, b) => (b === 2) - (a === 2))
but in Firefox the array is not sorted
不完全是,Firefox 可能使用不同的排序算法,这样排序器会以不同的顺序使用不同的参数调用。如果以下条件始终为真,则数组仅在所有不同的实现中正确排序:
sorter(a, a) === 0
sorter(a, b) === - sorter(b, a)
请注意,排序通常是 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))
假设我有一个要排序的数组,某个元素排在第一位,其余保持原样。
例如 [1,2,3,4],我希望 2 位于数组的开头
[1,2,3,4].sort((a,b)=> a == 2 ? -1 : 0)
在 chrome 中输出符合预期
// chrome
[2,1,3,4]
但在 Firefox 中输出不同,2 不是第一个
// firefox
[1,2,3,4]
您还需要正确处理 b
是 2
的情况:
.sort((a, b) => (b === 2) - (a === 2))
but in Firefox the array is not sorted
不完全是,Firefox 可能使用不同的排序算法,这样排序器会以不同的顺序使用不同的参数调用。如果以下条件始终为真,则数组仅在所有不同的实现中正确排序:
sorter(a, a) === 0
sorter(a, b) === - sorter(b, a)
请注意,排序通常是 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))