Where do I belong final piece missing

Tell us what’s happening:

I feel close on this one. I’m looping through the entire length of the first parameters array. Then pushing that Array and the second parameter into a new array, sorting it numerically, and once sorted getting the position of wherever the “num” parameter is in that new array…Problem is, the number parameter is in there twice. I’ve got to be making a simple mistake somewhere right? Is there a way to guide me without revealing the answer?

Your code so far


function getIndexToIns(arr, num) {
  newArr = []
  for(let i = 0; i < arr.length; i ++){
    newArr.push(arr[i],num);  
    newArr.sort(); 
    console.log(newArr)
    console.log(newArr.indexOf(num)); 
  }
  return newArr
}

console.log(getIndexToIns([40, 60 ], 50));//should get index 1 
}

getIndexToIns([40, 60], 50);

Your browser information:

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

Challenge: Where do I Belong

Link to the challenge:

Well now I just feel silly! Sorry about that. Edited.

Why you have to Sort while looping?

Num Is a fixed number AND Every element Will have the same num

Maybe i misunderstood the problem? the for loop is not sorting the numbers so I added a sort() method. Is that not correct?

You’re pushing num into the array through each iteration. You could find the index of the number less than num and then find a way to fix it into that point. Hope I didn’t reveal any spoilers with this answer.

1 Like

Thanks for the help guys. I kind of think I understand some of your guidance. If I am understanding correctly I need to push the num paramter before it goes into the for loop which i changed. I tried sorting the array prior to going into the array as well but it’s not sorting correctly. I’d say 80% of the challenge is passed but 3 parts, and I can’t understand why. If i figure out how to sort it appropriately, i’m sure i can get it to pass.

function getIndexToIns(arr, num) {
  arr.push(num);
  let sortArr = arr.sort(); 
  for(let i = 0; i < sortArr.length; i ++){
     console.log(sortArr[i])
      sortArr.includes(num)

  }
  return sortArr.indexOf(num); 
}

console.log(getIndexToIns([2, 20, 10], 19));//should get index 2 
1 Like

and now what should happen inside your loop?

for why it is not working, I suggest you look at your code with this:
http://pythontutor.com/javascript.html#mode=edit

and then research about the sort method