Basic Algorithm Scripting: Where do I Belong: Solution not passing tests

Tell us what’s happening:

The code below returns the correct indexes but it does not pass the tests. Could someone please explain why? Thank you.

  **Your code so far**

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

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

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36.

Challenge: Where do I Belong

Link to the challenge:

what do the failing tests say?

It passes none of the test, but when I check with console.log() I am getting the correct values. I also added a return arr.length in case the number is greater than all the numbers in the array, but it still does not pass a single test.

Do you mean to use <?

That if statement looks a little weird, you’re returning i in both cases.

Using a for...in loop isn’t the best choice btw, it shouldn’t be used to iterate over an array (and it also causes a certain test to fail): for...in - JavaScript | MDN

I edited my code to reflect my last attempt. So it now reads num <= arr[i]

Yeah I realized that so I tightened it by using <= instead. I changed for for...in loop to a regular for (var i...) loop and it passed the test. But now I’m curious as to why this caused the tests to fail… The results are the same, but it couldn’t pass the tests. Also then is it always more preferable to use for (var i...) instead of for...in or are there situations where the latter is more useful? Thank you.

So you sort from smallest to biggest and then return the first index that corresponds to a smaller value? That doesn’t make sense to me. You’d prematurely return 0 with that logic a lot.

It is comparing num <= arr[i] which is actually arr[i] >= num. So I am returning the first index at which arr[i] is equal to or larger to num.

Duh. I need to get some coffee stat!

Hahaha no worries, I got it to work by switching the for loop. Still curious as to why for (let i in...) did not pass the tests, though!

for in treats the array like an object, so it does not guarantee a certain order of the keys processed and it can include some additional keys that all objects have which aren’t really relevant to iterating over the contents.

Didn’t realize there were additional keys… Thank you. I’ll probably stick the to the ol’ reliable for (var i...) loop for now!

1 Like

In addition to what was already said, for...in converts i to a String, which is why it’s not a Number anymore.

As for loops, arrays have a variety of handy methods to loop over them (mainly .map, .forEach and .reduce). If you’re more comfortable with an “actual” loop, you can also use a for...of loop for arrays, but in this case it wouldn’t really do what you want, as you have no direct access to the index i.