Where do I belong- basic algorithm script problem(1)

Tell us what’s happening:
Hello, I am currently doing this challenge and the solution I have written seems to solve most of the challenge pass example but a few.

I would like some input on where I might have gone astray in the below solution.

  **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 arr.indexOf(num);
return num;

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

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

Challenge: Where do I Belong

Link to the challenge:

return arr.indexOf(num);

What do you expect to happen at this line?

to return the position of num in arr.

Well then you’ve got a bug because the number num is not guaranteed to be found in the array arr. In that case, indexOf will return -1.

You do not need to be using indexOf in the for loop, you already have access to the index as i. Making that change will increase performance, and it cannot cause the current bug, it however will not make your code pass as you if statement is not what you should be checking for and your final return value is incorrect.

the other is, what if num is smaller than everything?

I’m trying to understand what you mean by the if statement isn’t what I should be checcking for.

I have rectified that mistake with an else statement.

If num is less than or equal to the current element then you want return the index of that element, but you are currently saying to do that if num is greater than or equal to.

“ For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1)” That is what this is saying although its saying it such that if arr[i] is greater than or equal to num then you should return the index value of this element, and this is the same as saying if num is less than or equal to arr[i]

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