Where do I belong (Possible FCC problem)

Where do I belong (Possible FCC problem)
0

#1
function getIndexToIns(arr, num) {
  arr.sort();
  var less = 0;
  for (i=0;i<=arr.length-1;i++){
    if (num == arr[i]){
      less = i-1;
    } else if (num > arr[i]){
      less = i+1;
    }
  }
  return less;
}

It works for : getIndexToIns([3, 10, 5], 3)
getIndexToIns([5, 3, 20, 3], 5)
but not for: getIndexToIns([10, 20, 30, 40, 50], 30)
The 3 cases seem similar to me. I don’t understand why it doesn’t work for the third one. Could it be a problem with FCC?

Edit: That’s the only case it doesn’t work.


#2

Basic debugging skills - put a console.log after your sort and see what you’re getting. You’re misunderstanding how the [sort](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) functions works. Out of the box, it doesn’t work for numbers - you need to supply a callback function.

numbers.sort(function(a, b) {
  return a - b;
});

#3

By including the callback function you mentioned, now all 3 cases I mentioned above don’t work. What am I doing wrong still?


#4

Nevermind. Found the mistake: in line 6 the “-1” wasn’t needed.


#5

A post was split to a new topic: Why doesn’t my code for Where do I Belong challenge work?