Tell us what’s happening:
I’m working through my code. I got all but one test to pass. The failing test consists of an array of 4 numbers [5, 3, 20, 3]. I started debugging with console.log to find out what’s happening in the script. I can now see that the two 3s in the array share the same index of 0 and there is no index 1.

Is this the way it should be, seems odd to me.

Your code so far

function getIndexToIns(arr, num) {
let result = 0
let tempArr = arr.sort((a, b) => a - b);
console.log(`tempArr: ${tempArr}`)
for(let n = 0; n < tempArr.length; n++)
{
// if (num > tempArr[n] /* && num < tempArr[n + 1] */)
// {
console.log(n, tempArr.indexOf(tempArr[n]))
result = tempArr.indexOf(tempArr[n])
//}
}
//console.log(result)
return result
}
getIndexToIns([5, 3, 20, 3], 5);

Your browser information:

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

Challenge: Basic Algorithm Scripting - Where do I Belong

Yes, this is me debugging the code. This prints the value of n to the console and also the index of each item in the array. This is how I found out that the two 3s were sharing an index.

if you have the following array and line of code (which is inside a for loop that loops from 0 to 3 (so n is 0, 1, 2, 3 as we loop around)

tempArr is [3, 3, 5, 20]
result = tempArr.indexOf(tempArr[n])

then if we break apart the result statement
n is 0 for the first time in the loop
tempArr[0] is 3 (that’s the first element)
tempArr.indexOf(3) is 0 so result is 0 in the first loop

n is 1 now
tempArr[1] is 3 (that’s the 2nd element)
tempArr.indexOf(3) is 0 so result is 0 in the 2nd loop

Is this what you meant about sharing the same index?
(indexOf will give the index of the first occurrence unless you pass it a 2nd param to move the search forward. The 2nd param is the ‘fromIndex’ param)

MOST of the information you need can be gathered from the lessons in the course. There are times when the topics covered in the course need further research.