Hi everyone!
Trying to solve Where do I Belong Challenge in the Basic Algorithm Scripting section.
The code I have wrote perfectly works in this code editor: [https://eloquentjavascript.net/code/], but for some reason does not get accepted in the challenge.
Could anyone see what the problem could be?
function getIndexToIns(arr, num) {
let place;
for(var x in arr){
if (arr[x]>num) {
place=x;
break;
}
}
return place;
}
getIndexToIns([40, 60], 50);
Hi @s4ek1389, welcome to the forum.
The challange states
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.
For example, getIndexToIns([1,2,3,4], 1.5) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
Your code has the problem that it’s not odering the array before doing the check.
It would work in the case the array is already sorted, but there are cases in the tests where it’s not.
Also if none of the elements in the array are greater than the given number, what is getting returned is undefined. You might want to return something also in this case (eg. look at the test getIndexToIns([2, 5, 10], 15) should return 3.).
@simonebogni, thank you for your tips. I’ve added a sort method before my main code, but even after I sort the array, my solution still doesn’t pass the test, although in the other editor I get the exact output that is required by this challenge. Please have a look at the screenshots below. Any idea why this could be happening?