Where do I belong(0)

Where do I belong(0)
0

#1

Tell us what’s happening:
I’m creating a function that sorts the array parameter and inserts the number parameter in the position that would put it in numerical order. There’s a problem with my use of the sort() method but I’m not sure why.

Your code so far

function getIndexToIns(arr, num) 
{
  // Find my place in this sorted array.
  arr = arr.sort();
  for(var i = 0; i < arr.length - 1; i++)
    {
      if(num < arr[0])
        {
          return 0;
        }
      
      if(num > arr[i] && num < arr[i + 1])
        {
          return i + 1;
        }
      
      else if(num === arr[i])
        {
          return i;
        }
    }
  return arr.length;
  
}

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

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36.

Link to the challenge:


#2

.sort() treats the contents of an array as strings by default. You have to pass it a function that tells how it should sort an array of numbers.