Basic Algorithm Scripting - Where do I Belong

Tell us what’s happening:
My code fails to pass only one of the tests for this challenge and was wondering if there is any way to make it work the way it should.

  **Your code so far**
function getIndexToIns(arr, num) {
if (arr.length === 0) {
  return 0;
}
for (let i = 0; i < arr.length; i++) {
  arr[i] = arr[i].toString();
}
arr.sort();
for (let i = 0; i < arr.length; i++) {
  arr[i] = parseInt(arr[i]);
}
for (let i = 0; i < arr.length; i++) {
  if (num <= arr[i]) {
    return i;
  }
}
return arr.length;
}

getIndexToIns([40, 60], 50);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:103.0) Gecko/20100101 Firefox/103.0

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

This is not doing what you think it is. See this recent thread on this very issue. There is a good article referenced in the replies of how to use the sort method.

1 Like

Why are you converting the numbers to strings? This is not necessary at all.

I converted them to strings because the example I saw on the internet of how arr.sort() works was that it took an array of strings and sorted it based on the first character alphabetically, so I tried using that logic here. Now looking back at it, this would also be a problem with any two or more digit number that started with the same digit. I will look into the recent thread you linked to find out more of how sort() works, thank you.