NodeJs / Javascript integer array sorting

Max Kimambo
Thoughts of a software fundi
1 min readDec 22, 2016

So there is a gotcha when sorting arrays integer arrays in Javascript.

For example if you have an array

```
x = [ 1, 10, 2, 5 ]
```
doing x.sort() will return

```
[ 1, 10, 2, 5 ]
```

which kind of defeats the purpose as we can clearly its not sorted.
This happens because JS treats numbers in array as unicode point values and when we sort strings this totally makes sense.

If you want to get proper sorting you will have to pass a compare function to the sort method like so.

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

[ 1, 2, 5, 10 ]
```
Well what can we say, its just Javascript :)

Reference
[https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort)

--

--