# Array.sort() not sorting numbers correctly?

Array.sort() not sorting numbers correctly?
0

#1

Tell us what’s happening:

Trying to use the array sort function to sort

arr=[5, 3, 20, 3];
arr.sort();

but the result is
[20, 3, 3, 5]

when I expect
[3, 3, 5, 20]

Does anyone know why?

``````function getIndexToIns(arr, num) {
// Find my place in this sorted array.

arr.sort();

for (var i=0; i<arr.length; i++) {
if (arr[i]>=num) {
return i;
}
}

return arr.length;
}

getIndexToIns([40, 60], 50);
``````

Your Browser User Agent is: `Mozilla/5.0 (Windows NT 6.3; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0`.

https://www.freecodecamp.org/challenges/where-do-i-belong

#2

By default it sorts them ‘alphabetically’ - so 20 (or 2000) comes before 3.

To sort numerically, you pass your own comparison function.

`arr.sort(() => a - b)`

#3

Thank you for the info. The => syntax didn’t seem to work for me, so I end up doing:

arr.sort( function(x, y)
{
return x - y;
} );

#4

@r1chard5mith meant to write:

``````arr.sort((a,b) => a - b);
``````

#5

oops, sorry. Yes, that’s what I meant