Basic Algorithm Scripting - Where do I Belong

Tell us what’s happening:
Describe your issue in detail here.
Most of the points are correct, but I can’t figure out where I am going wrong.
Need help!

  **Your code so far**
function getIndexToIns(arr, num) {
console.log(arr.push(num))
// console.log(arr)
console.log(arr.sort())
for(let i=0; i<arr.length; i++){
  // console.log(arr[i])
  if(arr[i]===num){
    return i;
  } 
  
}

return num;
}

getIndexToIns([40, 60], 50);
  **Your browser information:**

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

Not sure if this will solve your problem, but one error I see is:

for(let i=0; i<arr.length; i++)

should be:

for(let i=0; i<arr.length -1; i++)

Remember, the array index starts at zero, so if your array has a length 5, the indexes are 0 to 4 (hence the need to subtract 1 in the stop condition).

1 Like

Why do you need this line? You should not return a num in any case

Do research about sort(). It doesn’t work like you want, when dealing with numbers. Some stuff should be written in parentheses.

That looks fine(except the part which was mentioned above), but there is alternative: one could use indexOf() here