Bug with Sorting Arrays Where do I Belong

Tell us what’s happening:
My code worked for every test case except getIndexToIns([5, 3, 20, 3], 5) (rather than returning 2, my function returns 0).

As part of debugging, I checked the value of sorted with the above input, and I see that this array does not sort in order.

Can someone help me understand what’s going on?

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var sorted = arr.sort();
  var i = 0;
  while (i < sorted.length){
    if (sorted[i]<num){
      i++;
    }
    else {
      break;
    }
  }
  
  /*
originally the part below was "return i;"— I changed it for debugging purposes
  */
  console.log(sorted);
}

getIndexToIns([5,3,20,3], 5);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong/

i think your sort method is not working? It returns this:
[ 20, 3, 3, 5 ]

which is definitely not sorted. You should re-write your sort like this instead:

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