Where do I belong problem - very stuck

This is yielding probably like half of the tests wrong. Let me know what you see as a problem. Thanks for any and all help - really banging my head against the wall on this one


function getIndexToIns(arr, num) {
arr.sort(function(a, b) {
  return a - b;
});


for (let i = 0; i < arr.length; i++) {
  if (arr[i] <= num) {
    return i;
  } else {
    return arr.length;
  }
}
}

console.log(getIndexToIns([2, 20, 10], 19));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36.

Challenge: Where do I Belong

Link to the challenge:

Example test case you are looking at is a good one to concentrate on and figure out what might be wrong. Consider what function is doing and whether that’s what it should do at that point. You can walk through the function step-by-step and follow the operations - after the array is sorted first number in array to check num against is 2 - see if what’s happening is what you’d expect it to do. Then consider the next number in array and so on.

Hey btcannavo!

I see two issues with your code :slight_smile:
Firstly, you are sorting your array but not storing the return value anywhere! You need it to be: arr = arr.sort(…) to update the value off arr

Secondly, your for loop is doing the following…

if arr[0] <= num : return 0
if it’s not meant to be at position 0, return the array length

so it’s not iterating, it’s doing iteration one and being ejected by the return statement

Just put the return arr.length outside of the for loop and when the code is executed it will either find a solution in the for loop and return that value, or return the arr.length.

Finally have a look at the logic of your if condition - no spoilers but it’s not quite right! :slight_smile:

sort method does sorting in place, it doesn’t need to be reassigned.

My mistake, but still good practice for other array methods especially when chaining right?