Strange sorting of array when using Array.prototype.sort in Chrome

折月煮酒 提交于 2019-12-04 04:02:03

问题


I have found an oddity when using Array.prototype.sort() on an array of numbers and I'm not sure what's causing it.

My goal is to reverse an array using sort (not using reverse) so I can chain it like so:

const shouldReverse = Math.random() > 0.5,
      result = foo().bar().map(...).reverseIf(shouldReverse);

I believe I should be able to achieve this using sort, which seems to work in some cases but not others.

Here is a working example:

const myArray = ['a', 'b', 'c', 'd'],
      mySortedArray = myArray.sort(() => 1); 

console.log(mySortedArray);
["d", "c", "b", "a"]

And a non-working example:

const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k'],
      mySortedArray = myArray.sort(() => 1); 

console.log(mySortedArray);
["f", "k", "a", "j", "i", "h", "g", "b", "e", "d", "c"]

This only happens in Chrome and only when there are more than 10 elements in the array — could it be some form of optimisation in Chrome's V8 engine?


回答1:


I believe I should be able to achieve this using sort

No, you should not. You are looking for reverse.

For your specific examples, which are already sorted in ascending order, you can achieve a reversal by passing a comparison function that leads to a descending order, but this won't work for arbitrary arrays with arbitrary values.

myArray.sort((a, b) => (a<b)-(b<a));
myArray.sort(() => 1)

That's a totally inconsistent comparison function. You can't expect this to work.

This only happens in Chrome and only when there are more than 10 elements in the array

That's because the JS engine in Chrome uses a different sort algorithm for small arrays, which does its comparisons in a different order and apparently always with the higher indexed item in the second argument. You just got lucky.



来源:https://stackoverflow.com/questions/39751432/strange-sorting-of-array-when-using-array-prototype-sort-in-chrome

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!