Tell us what’s happening:
Why is this code wrong?
Your code so far
function getIndexToIns(arr, num) {
arr.sort(function(a,b){return a-b;});
for (let i in arr){
if(arr[i]>num){
return i;
}
}
return arr.length;
}
console.log(getIndexToIns([2, 20, 10], 19));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36
.
Challenge: Where do I Belong
Link to the challenge:
Learn to code. Build projects. Earn certifications.Since 2015, 40,000 graduates have gotten jobs at tech companies including Google, Apple, Amazon, and Microsoft.
Hey @anshullaikar ,
You see that the console spits out that it is outputting the right answer, but the test doesn’t actually sees it as the actual answer, which is a number.
Seeing this repl, your function is outputting a string, not a number?? I don’t know why
1 Like
Don’t use the for…in loop with arrays. Use the for…of loop.
The i
variable in the for…in loop is a string.
function getIndexToIns(arr, num) {
arr.sort(function(a,b){return a-b;});
for (let i in arr){
console.log(typeof i); // string
if(arr[i]>num){
return i;
}
}
return arr.length;
}
2 Likes
Also, remember that the num
and the number in the array can be the same value.
arr[i]>num
this only checks that the array number is larger than num
(and not also equal).
1 Like