Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

[6,-2,2,-7].sort()

Result : [-2,-7,2,6]

Ladies and Gentlemen, the lingua franca of web programming.



new Int32Array([2,7,-2, -7]).sort()

Result: Int32Array [-7, -2, 2, 7] (4)

The problem is you can put anything in array and JS can't really check that "everything here is a number", so it uses string as a common type because everything can be converted to string.

we need proper typed arrays, like Int8/16/32Array but with any class, not just int. The class itself will then define how to compare instances (python's __gt__ and so on).


Because js sort works on string. for numeric sort try:

`[6,-2,2,-7].sort( (a,b) => a-b)`


It would be cool if an array of numbers was sorted by numeric value by default, instead of the values being sorted alphanumerically, yes, that’s a gotcha.


Someone didn't read the docs.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: