'Where do I Belong' Challenge confusion

Tell us what’s happening:

If you run my code on this challenge, you see it only throws an error in one test case. I’m trying to understand why my code would work for all the other test cases but not for this one and it has stumped me. Any help would be appreciated.

Your code so far


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

}

console.log(getIndexToIns([5, 3, 20, 3], 5));

Your browser information:

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

Challenge: Where do I Belong

Link to the challenge:

try console.log(arr) inside the array

you could fix that, or go an other root: you don’t need to sort the array, you could get the index by counting how many numbers are smaller than the number to insert

1 Like

Thanks for responding so quick! I didn’t realise .sort() doesn’t work for sorting numbers higher than 10 as it only looks at the first digit, so a function is needed such as ‘function(a, b){return a-b}’