I have some questions on Where do i belong

I have a few questions regarding the “Where do I belong” problem.

First, why does the sort function has to be a call back function.
What is the sort (call back) function doing there. i.e.

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

why do we have to “return a-b”

While applying the sort function just like this:

arr.sort();

it does not sort this array
[5, 3, 20, 3]
but sorts every other array just fine, why is that?

here is my complete solution.

function getIndexToIns(arr, num) {
  // console.log(arr.sort());
  arr.sort(function(a, b) {
    return a - b;
  });
  console.log(arr)
  let i=0;
  for(i=0; i<arr.length; i++){
    if(num<=arr[i]){
      console.log(i);
      return i;
    }
  }
  return i; 
}

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

You’ve missed some of your code out here when you’ve copied it across, applying it how?

1 Like

Thank you. The link you provided really helped me understand the sort callback function.
What i intended to write was
arr.sort(); using sort without the function (a, b) { return a-b}; works fine sorting arrays but does not work for one in specific, i.e. [5, 3, 20, 3]

Once again, thanks this helped a lot.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.