Reputation: 15
Why this happens? I'm doing exercise on FreeCodeCamp (Return the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. The returned value should be a number.) I know there are better ways to do this but I'm interested in this problem. This is my code:
function getIndexToIns(arr, num) {
let pos = 0;
arr.sort((a, b) => a - b);
console.log(arr);
for(let arrs in arr) {
if (num == arr[+arrs]) {
return pos = +arrs;
}
else if (num < arr[+arrs]) {
pos = ((+arrs));
return pos;
}
else {
return "why"
}
}
return 0;
}
console.log(getIndexToIns([2, 20, 10], 19));
console.log(getIndexToIns([2, 5, 10], 15));
Upvotes: 0
Views: 101
Reputation: 2028
The problem is in your if-else-if
flow. The if-else-if
work procedure is like below:
if
is false, check next else if
conditionelse if
condition is also false, will check the next else if
condition if ther is any.else if
condition, it will find else
condition and work on that, if not found, will work on rest of statementsSo, in your case, if first if
is true, the look works only once, if that is false, then check next else if
and if it is true, the loop ends, otherwise directly goes to else
condition and returns from here running the loop only once. That's why it runs only once.
Upvotes: 1
Reputation: 66
The problem is you are returning "why"
at the start of the loop, so basically 19 would be compared to 2, and when it finds that 19 === 2
is false and 19 < 2
is false, it returns "why"
and gets out of the function without looping through the elements, same goes for the second array.
Try to use an array in which all the values are bigger than num
and you will see that it gives you 0.
the solution would be to erase the third else altogether.
Hope this helped you.
Upvotes: 1