GOTO 0
GOTO 0

Reputation: 47781

Why is -1 sorted before -Infinity in Javascript?

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?

Upvotes: 9

Views: 1275

Answers (1)

Bergi
Bergi

Reputation: 664936

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

Upvotes: 13

Related Questions