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?
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.
That's a totally inconsistent comparison function. You can't expect this to work.
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.