Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Array.sort() not working in Firefox

say I have an array that I want to sort, that a certain element will be first, and leave the rest the way it is.

for example [1,2,3,4] and I want the 2 to be at the beginning of the array

[1,2,3,4].sort((a,b)=> a == 2 ? -1 : 0)

in chrome the output is as expected

// chrome
[2,1,3,4]

but in Firefox the output is different and the 2 is not first

// firefox
[1,2,3,4]
like image 302
Mordy Stern Avatar asked Mar 16 '26 18:03

Mordy Stern


1 Answers

You also need to handle the cases were b is 2 properly:

 .sort((a, b) => (b === 2) - (a === 2))

but in Firefox the array is not sorted

Not quite, Firefox might use a different sorting algorithm, such that the sorter is called with different arguments in a different order. The array is only sorted correctly in all different implementations if the following conditions are always true:

  sorter(a, a) === 0
  sorter(a, b) === - sorter(b, a)

Note that sorting is usually O(n log n) average case (though it could be better if a lot of elements are equal), whereas the problem can be solved in O(n):

 const withoutTwo = array.filter(it => it !== 2);
 const result =
   Array.from({ length: array.length - withoutTwo.length }).fill(2)
    .concat(withoutTwo);
like image 152
Jonas Wilms Avatar answered Mar 19 '26 15:03

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!