Can't get passed this one

if the number is bigger then the biggest number of the array, test fails…
Help is appreciated.
Thanks!!

Your code so far


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

    if (sortedArr.length == 0 || num < sortedArr[0]) {
    return 0; }

for (let i = 0; i < sortedArr.length - 1; i++) {
  if (num == sortedArr[i]) {
    return sortedArr.indexOf(sortedArr[i]);
  }
   if (num > sortedArr[i] && num < sortedArr[i + 1]) {
     return sortedArr.indexOf(sortedArr[i + 1]);
   }
}
return sortedArr[sortedArr.length];
}

getIndexToIns([40, 60], 50);

Your browser information:

User Agent is: Mozilla/5.0 (X11; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0.

Challenge: Where do I Belong

Link to the challenge:

I don’t understand this line:

return sortedArr[sortedArr.length];

First of all, it’s nonsensical - by definition this will be undefined since the last index in any array is its length - 1. But did you want to return an element from the array? Is that what you wanted?

With a small tweak to this line, I was able to get your code to pass.

You are absolutely right mate, I forgot to change that line to the index of the last element plus 1 thus changing it to sortedArr.length solved the problem. Thanks!