Where do I belong - my code seems to correct, yet

Tell us what’s happening:

Even though my code gives the correct data on each test when logging it to the console, it says that it does not pass many of the tests.

  **Your code so far**

function getIndexToIns(arr, num) {
 arr=arr.sort(function(a,b){return a-b;});
for(let i in arr){
    console.log(i);//Just for debugging, remove later.
    return i;
console.log(arr.length);//Just for debugging, remove later
return arr.length;
getIndexToIns([40, 60], 50);
  **Your browser information:**

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

Challenge: Where do I Belong

Link to the challenge:

Does this do what you think it does?

yes, I think so,
i.e. when I give the function:

console.log(getIndexToIns([2, 20, 10], 19));

It will first sort it to [2,10,20]

It returns true on the first element bigger or equal than the number given (19), so then it returns that position value (i): 2… and shouldn’t it break the loop with the return?

And that is what I get in console: 2

Did you read the link I included at all?

sorry, my bad.

I mistook the link for an ad.

Will read it.

1 Like

Ok, I read it.

What I though a for…in did:
Iterate through objects properties or arrays keys assigning them to the binding I had set.

What after reading the link I think a for…in does:
Iterate though “string” object properties names, accidentally it does also with arrays and array keys, but the catch is that, since this kind of loop is thought for object properties and their string names, it assigns the key as a “string”, and not as a number.

In conclusion, as I have already checked introducing a
console.log(typeof i); after the for…in, the “numbers” it’s showing in my console are actually strings, since I am returning the i binding,
therefore failing the tests.

So, when I swap over to a different type of loop through your array, your exact logic works fine. You had good logic but bad syntax.

The new code, fixing the issue by removing my fancy for…in loop with a regular for loop.

Thanks for the help JeremyLT

1 Like

Yeah, sometimes these loop constructs designed for objects work funny on an array.

If you want to try something a little fancy, you can try this one:

I kinda see how that could make the for…in loop work.

Thanks again JeremyLT

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