Https://www.freecodecamp.com/challenges/where-do-i-belong

function getIndexToIns(arr, num) {
// Find my place in this sorted array.

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

}
}
return arr.length;
}

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

can you please tell me whats wrong with my code? i cant get the output for this one.

Your arr.sort() is the problem. You need read the information in the sort function (available at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort). You need to add a compare function. Currently, without the compare function, the array is sorted according to each character’s Unicode code point value, according to the string conversion of each element. If you add a console.log(arr) on the line following the sort I mentioned above, you will see what the array looks like after sorting but before going into the for loop logic.

Also, instead of sorting the array multiple times in the for loop which is not efficient, just move the sort to right before the for loop, so it only sorts one time.

1 Like

try this:
function getIndexToIns(arr, num) {
// Find my place in this sorted array.

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

}
}
return arr.length;

thank you so much!!! i finally got it :smiley:

thanks a lot :slight_smile: i got it now