Basic Algorithm Scripting - Where do I Belong

Tell us what’s happening:
Describe your issue in detail here.
In my own instance of VSCode this works. On freeCodeCamp I fail almost every test. Any ideas as to what’s happening?

Your code so far

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

getIndexToIns([40, 60], 50);

Your browser information:

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

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

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

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

What do you see here? for..in uses string keys, not numeric keys.

I would look a little closer at the documentation for the for...in loop. Particularly, what type of value the counter variable (index in this case) is. You can test this using the typeof operator.

Ahh, @JeremyLT must have added this to his post while I was writing mine. So ya, what his hint says.

2 Likes

Yeah, I thought my hint was possibly a bit too obtuse and added more.

2 Likes

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