Where do I Belong (Query about the status of the num insert)

Tell us what’s happening:
I’m on the right track, but I have a question about num before I go further.

num is the number to be inserted into the array in between the highest number it is lower than and the lowest number it is lesser than.

In Hint 2 that FCC provides it says that you’re supposed to look for the first number that is bigger than num and return the index of that.

I’ve done that and I haven’t passed all the tests and I’m a bit stuck.
I didn’t want to use a for loop for this activity as I was also trying to solve the challenge in the simplest manner.

Am I wrong? Is a for loop just the best way to go about it?

Thanks so much for your comments.

Your code so far


function getIndexToIns(arr, num) {
  var result;
  //sort the numbers
  arr = arr.sort(function(a,b){
    return a-b;
  });
  console.log(arr)
  //within the sorted array discover the lowest number that is greater than num
if(arr.length<num<arr.length){
 var insNum = arr.indexOf(num);
  console.log(insNum)
}
return insNum;
}

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/70.0.3538.102 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong

So your if statement is… iffy.

Are you trying to check if arr.length < num or if num < arr.length? Somehow you’re doing both, and I think you just broke your browser’s brain…

1 Like

First ‘push’ num to the arr array and then use the sort, in this way the num is positioned to the expected index.
Then query if num is in the array (You know is there because you have pushed the number in the array and sort did the job to position the number to the correct index. You just need to return the index for num to complete the challenge. ) and return the index position of num via arr.indexOf(num), there is no need for any sort of loop.

function getIndexToIns(arr, num) {
  arr.push(num) && arr.sort((a,b)=>a-b);
   return arr.indexOf(num);
}

Okay. That was really good advice @snowmonkey & @GeorgeCrisan

Also, @snowmonkey I’m still laughing at your comment “I think you just broke your browser’s brain” :rofl:

Thank you both.

1 Like