What is .sort(callbackFunction)?

Tell us what’s happening:

What is .sort(callbackFunction) ? How does .sort(callbackFunction) work in this code ?
I tried code tracing so parameter a and b in function(a,b) refers to 5 and 3 in arguments ? Is it like that? I am confused.

Your code so far


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

for (var a = 0; a < arr.length; a++) {
  if (arr[a] >= num) return a;
}

return arr.length;
}

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

Challenge: Where do I Belong

Link to the challenge:

1 Like

sort is a built in m,ethod that sort an array using a callback function to compare the elements in the array two by two and ordering based on what the callback returns, saying that the two elements are called a and b, if the caalback returns less than 0 than a comes before b, if the callback returns more than 0 than a goes after b, and if they are equal the callback returns 0
to order numbers a common way is to return their difference as that goes automatically to the more than 0/less than 0 of before

for more infos this is the documentation on sort
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

4 Likes

I get it now. Thank you.

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