Basic Algorithm Scripting - Where do I Belong - Code failing for particular inputs

Tell us what’s happening:

Describe your issue in detail here.

Can you tell what’s wrong with my code. It works for every test example except the one that wrote below. And I am unable to understand. It happens for the input array which has duplicate elements.
Code so far

function getIndexToIns(arr, num) {
 arr.sort();
 let i;
// console.log(arr);
 for (i=0; i<arr.length;i++){
     if(arr[i]>=num&&arr[i]!=arr[i+1]){
       continue;} 
     else if(arr[i]>=num&&arr[i]!=arr[i+1]){
       return i;}
 }
 return i;
}

getIndexToIns([5, 3, 20, 3], 7); //Failed
getIndexToIns([10, 20, 30, 40, 50], 35) // passed
getIndexToIns([10, 20, 30, 40, 50], 30) // passed
getIndexToIns([40, 60], 50) // passed
getIndexToIns([3, 10, 5], 3) // passed
   **Your browser information:**

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

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

Are you sure?

I just run your code.

It failed like this:

// running tests
getIndexToIns([10, 20, 30, 40, 50], 35) should return 3.
getIndexToIns([10, 20, 30, 40, 50], 30) should return 2.
getIndexToIns([40, 60], 50) should return 1.
getIndexToIns([3, 10, 5], 3) should return 0.
getIndexToIns([5, 3, 20, 3], 5) should return 2.
getIndexToIns([2, 20, 10], 19) should return 2.
// tests completed

If you want to sort numbers you need to write callback function for sort() properly.

1 Like