Understanding this exercise: Where do I Belong

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])
  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/ Safari/537.36

Challenge: Basic Algorithm Scripting - Where do I Belong

Link to the challenge:

doesn’t this statement just equal n?
(the index of the item at position n is n?)

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.

The array is not nested. It’s a simple array.

1 Like

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)

Ah yeah my bad, looked too quickly at the issue and mistook the parens for brackets.

1 Like

^^ interesting information here. I will move accordingly with this info.

Thanks to @hbar1st I was able to move on from this one. I used:

Glorious day


Yes! this is me And I am new here please help me for getting information

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.

Google search for more education and examples

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.