Basic Algorithm Scripting: Where do I Belong one failed test

I’ve passed every test bar 1 in the Basic Algorithm: Where do I belong lesson and I can’t think for the life of me why it isn’t passing.

getIndexToIns([5, 3, 20, 3], 5) is sorted then the num is checked if it is smaller than the last element of the sorted array.

If so, it returns the highest index position which satisfies this criteria.

But, for some reason, it’s not working with this particular test, returning 4 rather than 2 and I’m not sure why.

Your code so far


function getIndexToIns(arr, num) {
let sortedArray =  arr.sort()
let highestIndex = (element) => element >= num; 
 if (num < sortedArray.slice(-1)[0] ) {
return sortedArray.findIndex(highestIndex);
 }
else {
 return sortedArray.length
}
}
getIndexToIns([40, 60], 50);

console.log(getIndexToIns([5, 3, 20, 3], 5))
//should return 2


Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36.

Challenge: Where do I Belong

Link to the challenge:

Hey. I just finished working through the Basic Algorithm Scripting section this morning and there’s a much easier way to pass this test - you don’t actually need to sort the array at all, you just need to find out how many elements in the array are smaller than num - because if the array was sorted, that’s how many elements would be to the left of it. Does that make sense?

1 Like

Hmm thanks I’ll give it a try, maybe I was overcomplicating it

Okay that was really straightforward through that method, guess I was just thinking it through the wrong way. Thanks

1 Like