Basic Algorithm Scripting: Where do i Belong SOLUTION

I don’t understand why this doesn’t give the expected result.

function getIndexToIns(arr, num) {
    let sortedArr = arr.sort();
    for (let i = 0; i < arr.length; i++){
       if (sortedArr[i] <= num) {
         if (num <= sortedArr[i+1]) { 
           return i;
         }
        }
       } 
    }
  
  let res = getIndexToIns([10, 20, 30, 40, 60], 50);

  console.log(res);

Very helpful answer.
Thank you, will try to adjust accordingly.

Can I also have some help with why my solution isn’t working? Here is my code, which works for half of the tests:

function getIndexToIns(arr, num) {
var counter = 0;
arr.sort(function(a, b){
return a-b;
})
for (var i = 0; i < arr.length; i++) {
if (num > arr[i]) {
counter += 1;
}
arr[counter] = num;
}
return counter;
}

getIndexToIns([40, 60], 50);

Thank you in advance!