Why my solution is not working with all tests

Hey, I come up with this solution and it should work with all tests why it is not?


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

console.log(arr)

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


return arr.length
}


getIndexToIns([2, 20, 10], 19)
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/101.0.4951.67 Safari/537.36

Challenge: Where do I Belong

Link to the challenge:

this loop isn’t return what the test require. the test require where do the num belong, not the number lower than the num

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

looking at your code your logic is sound. you are trying to stop after finding the lower number by returning it, then assign lower number position.

if so remember that for loop is increasing the value of i, and i is compared to arr.length, so you can use i to know the position of the lower number.

although the logic is sound, this isn’t how return work for more

return stops the function after returning a value

so remove return in the for loop then add console.log(arr.length) after the for loop.

this won’t let you pass the test, but at least you now know, where was the trouble.

this is last edit, I hope🤣. although if(arr[i] < num && arr[i + 1] > num)
passes the description examples, the step requires more from you. you have to keep in mind, what if element in the array equals to num, or what if the array is empty

How am I losing my ability to use comprehensive english by the day, while spending 3 days trying to fix typos in the repo🤦

what tests are you failing?

what the challenge want you to return?

have you tested what the function returns for the cases in which you fail the tests?

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