9

Out of curiosity, what rules apply here exactly?

alert([-Infinity, -1, Infinity, 0, 1].sort());

Outputs: -1, -Infinity, 0, 1, Infinity

JSFiddle: http://jsfiddle.net/8tVGb/


How is it that -Infinity gets sorted between -1 and 0?

Maciej A. Czyzewski
  • 1,539
  • 1
  • 13
  • 24
GOTO 0
  • 42,323
  • 22
  • 125
  • 158

1 Answers1

13

If you don't use a custom compare function, sort always converts the items to strings and orders them lexicographically. Use

….sort(function(a,b){ return a-b; })

See also How to sort an array of integers correctly

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Just curious, but won't `-1 - -infinity` yield NaN, or -infinity or some other nonsensical result in JavaScript? So for infinities and NaN's `a-b` is no good? – Lawrence Dol Jul 31 '13 at 02:33
  • 1
    @SoftwareMonkey: Nope, `-1 - -Infinity` yields `Infinity` which *has* a sense - it's greater than zero so `b` should come before `a`. Infinities compare fine, only `NaN` would cause problems. – Bergi Jul 31 '13 at 02:36
  • 3
    Whenever you're working with a language that has numberical overflow wrap-around (where `Integer.MAX + 1 == Integer.NEGATIVE_MIN`), @SoftwareMonkey is right. In those cases, this technique will always work: `sort(function(a, b){ return (a > b ? 1 : (a < b ? -1 : 0)) }` – Kevin Jul 31 '13 at 03:35
  • @Kevin: OK, but JavaScript is not such a language :-) – Bergi Jul 31 '13 at 14:06
  • Thanks for the precise answer :) – kooskoos Jan 11 '22 at 14:55