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

I found weirdness when using Array.prototype.sort()numbers in an array, and I'm not sure what causes it.

My goal is to rotate the array with sort(without using reverse) so that I can chain it like this:

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

I believe that I could achieve this using sortone that seems to work in some cases, but not in 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 if the array contains more than 10 elements - could it be some kind of optimization in Chrome V8?

+4
source share
1

, , sort

, . reverse.

, , , , , .

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

. , .

Chrome , 10

, JS- Chrome , , -, . .

+3

Source: https://habr.com/ru/post/1656108/


All Articles