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.
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.
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
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.
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.
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.