Where do I Belong - What's wrong with my code? Infinite loop?

This logic seems sound to me…can someone help me figure out what the logical error is here? I don’t understand! Thanks in advance

  **Your code so far**

function getIndexToIns(arr, num) {
let result = arr.sort((a,b) => a-b);
for (let i = 0; i < result.length; i++) {
  if (num > result[i] && num < result[i + 1]) {
     result.splice(i,0,num);
  }
  }
}


console.log(getIndexToIns([20,30,40,70,90], 50));
  **Your browser information:**

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

Challenge: Where do I Belong

Link to the challenge:

You should not modify an array as you iterate over it. That’s a good way to produce unexpected results or an infinite loop.

Would you mind talking through exactly what’s breaking in my code?

Try this

function getIndexToIns(arr, num) {
  let result = arr.sort((a, b) => a - b);
  for (let i = 0; i < result.length; i++) {
    console.log(result.length); // PAY ATTENTION TO THE LENGTH OF YOUR ARRAY!
    if (num > result[i] && num < result[i + 1]) {
      result.splice(i, 0, num);
    }
  }
}


console.log(getIndexToIns([20, 30, 40, 70, 90], 50));

Do not mutate an array as you iterate over it. It makes huge messes;

Gotcha. So I took the mutating code out of the for loop and did this. It’s generating an empty array. Why is that?

function getIndexToIns(arr, num) {
  let result = arr.sort((a,b) => a-b);
  let insertIndex;
  for (let i = 0; i < result.length; i++) {
    console.log(result.length);
    if (num > result[i] && num < result[i + 1]) {
       insertIndex = i;
    }
    }
  return result.splice(insertIndex,0,num);
}

console.log(getIndexToIns([20,30,40,70,90], 50));```

Why are you returning an array?

getIndexToIns([10, 20, 30, 40, 50], 35) should return a number.

1 Like

Good catch…I figured it out. Thanks for all the help, Jeremy LT!!

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