Array.sort() not sorting numbers correctly?

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?

Your code so far

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 information:

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

Link to the challenge:
https://www.freecodecamp.org/challenges/where-do-i-belong

1 Like

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)

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;
} );

oops, sorry. Yes, that’s what I meant :+1: