Where do I Belong-2 conditions are not matching help me out

Tell us what’s happening:

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  var index=0;
  arr=arr.sort();
  if(arr[arr.length-1]<num) {index=arr.length;}
  else{
    for(let i=0;i<arr.length-1;i++){
      if(arr[i]==num) { index=i;break;}
      else if(arr[i]<num && arr[i+1]>num){
        index=i+1;
      }
    }
  }
  return index;
}

console.log(getIndexToIns([5,3,20,3], 5));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.96 Safari/537.36.

What conditions aren’t match? Can you post a link to the challenge?

I am unable to share link.FCC is not allowing me. Can you please check Where I Belong challenge from algorithm scripting from javascript section?

I didn’t really look at the code but your sort is likely not doing what you expect it to.

[5,3,20,3].sort()
[20, 3, 3, 5]

[5,3,20,3].sort( (a,b) => b - a)
[20, 5, 3, 3]

Thanks it worked …sort was replaced by sort ((a,b)=>a-b)

Cool, I would suggest getting into the habit of logging and using the debugger in the browser. Check that your data and any operations you perform on it does what you expect it to.

That way you also won’t waste time looking at a logical problem for errors when the problem is in the data your feeding the logic.

1 Like