1

According to Array.prototype.sort() description:

Since version 10 (or EcmaScript 2019), the specification dictates that Array.prototype.sort is stable.

It won't swap [a,b] if a == b. It also won't swap them if a < b.

Then a short function like this looks valid and universal:

arr.sort( (a,b) => a>b )

And before that a short valid one was:

arr.sort( (a,b) => a>b||-1 )

Is that a correct and universal way to sort an array? Or am I missing something, and it won't work in some cases?

(By "universal" I mean it works for any array type: array of numbers, array of strings...)

pycoder
  • 477
  • 3
  • 10
  • 2
    have you read this: https://stackoverflow.com/questions/24080785/sorting-in-javascript-shouldnt-returning-a-boolean-be-enough-for-a-comparison – Nina Scholz Jun 10 '21 at 18:13
  • 1
    It won't work if you're sorting an array of objects and want to sort specifically on some property of the objects. Nor will it work if you want to sort on an array of arrays by array length... – Alexander Nied Jun 10 '21 at 18:14
  • @Nina Scholz That question was asked in 2014. Probably doesn't apply to EcmaScript 2019. And they haven't tested the `a>b||-1` function. – pycoder Jun 11 '21 at 11:31
  • It's just I noticed that for a universal function people suggest something like `Number(a>b)-0.5` or `ab)` or even `Number(a>b) - Number(b>a)`. So I was curious, is there a reason for such a complex solution, or I can use a much simpler (and probably FASTER) one? – pycoder Jun 11 '21 at 11:41

0 Answers0