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

前端 未结 1 1377
谎友^
谎友^ 2021-01-19 23:53

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

相关标签:
1条回答
  • 2021-01-20 00:06

    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.

    0 讨论(0)
提交回复
热议问题