Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 706
GOTO 0 Avatar asked Jul 31 '13 01:07

GOTO 0


1 Answers

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

like image 167
Bergi Avatar answered Sep 25 '22 18:09

Bergi