Basic Algorithm Scripting - Where do I Belong

Tell us what’s happening:
What is the issue in my code? It is not passing the single test.

Your code so far

function getIndexToIns(arr, num) {
  arr.sort((a, b) => a - b);
  for(let elem in arr){
    if(arr[elem] >= num)
    {
      // console.log(elem)
      return elem;
    }
  }
  // console.log(arr.length);
  return arr.length;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

Your for-in loop is iterating over the actual array elements, not the array indices. So if your array is [10, 20, 30, 40, 50], your for loop will iterate through 10, 20, 30, 40, 50, not 0, 1, 2, 3, 4. You should replace it with a simple for loop - for (let i = 0; i < arr.length; i++) which will iterate over the array indices.

elem in the above code is indices only. I checked it by console.log.

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