Where do I belong .......help plzz

Tell us what’s happening:

Your code so far

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.

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

getIndexToIns([5, 3, 20, 3], 5);

 

Your browser information:

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

Link to the challenge:
https://www.freecodecamp.org/challenges/where-do-i-belong

what is wrong with this code the above input is not passing the test…!!

There are 2 problems that I see ,

Number 1 is with the sorting function that you are using, note the following from MDN

The sort() method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.

That is why It’s better to go with the callback function of sort() method always and specify how you want your sorting to be done, for example to sort ascending you could use

arr.sort((a,b)=>{
 return a-b;
})

read more about sorting with the callback function here:

The second problem that I see is with your comparison function and your if statement , you maybe overthinking it, if the number you are checking is less than or equal to the array element that it is being checked against, that is sufficient to break the loop and return the index. You don’t really need anything ‘else’ (pun intended)

hope that clarifies if not let me know…

oops just saw @camperextraordinaire response too

Ah. I see he wasn’t at first, I copied the code was doing something else and continued writing, this was the original code I copied ,