Basic Algorithm Scripting - Where do I Belong

Tell us what’s happening:
Describe your issue in detail here.

Hi, I don’t understand why the num here skips the if statement and goes straight to the else statement. It works for getIndexToIns([2, 5, 10], 15) and getIndexToIns([3, 10, 5], 3), but not others.

Your code so far

function getIndexToIns(arr, num) {
  arr.sort((a, b) => a - b);

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

console.log(getIndexToIns([10, 20, 30, 40, 50], 35));


Your browser information:

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

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

here’s one of the failing tests:

Failed:getIndexToIns([10, 20, 30, 40, 50], 35) should return 3

Your code:

Just go thru this step by step.

i=0 and arr[0] is 10
is 10 >= 35, no return 5

So clearly that’s wrong… Try again?

ohhhh I see, thank you for pointing it out!

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.