Where do I belong Challenge Help

Where do I belong Challenge Help


Hi there. I can’t figure out where I’m going wrong?? Please help

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr = arr.sort(function(a, b){return a-b;});
  var answer = 0;
  for (var i=0; i<arr.length; i++) {
    if (num<=arr[i]) {
      answer = arr.indexOf(arr[i]);
  return answer;

getIndexToIns([10, 20, 30, 40, 50], 30);


nearly there … what is happening it is checking all of the numbers in the arr in the for loop and assiging the result of the ones that pass the if to the variable answer but you forgot if say arr[2] meets the criteria it assigns it to answer then goes and checks arr[3] if this is true it now overwrites answer with this .etc etc

delete your return statement
and change line … answer = arr … to … return arr.indexOf(arr[i])
now when the if in your for loop finds a num it returns it and dose not continue overwriting the answer.

tip put console.log statements in your for loop and watch what happens and this will make things easier as you can see what happens … i generally use repl.it as console.log() statements show up in result screen which makes it handier.


Yess got it! Thanks :slight_smile: