Skip to content
Advertisement

JavaScript sort value by arrow function

in JavaScript , we can use array.sort((a, b) => a-b) to sort the array in increasing order.

I know that we pass a function into the sort to customize it.

array.sort( function(a, b) {
    return a - b
})
function compare(a, b) {
  if (a < b ) {
    return -1;
  }
  if (a > b ) {
    return 1;
  }
  // otherwise a == b
  return 0;
}
// or like here
 
var array = [2,1,11];
array.sort(compare);

It is said when a - b = positive value, then place b in the first, like (b, a) descending order. I wonder how this positive value influence the order of sort ? If it is said -1 means the increasing, 1 means the descreasing ?

Advertisement

Answer

The sort function applies some kind of sorting algorithm such as bubble sort or quicksort to the data.

These algorithms all repeatedly compare two values in the array until the whole array is sorted. (Different algorithms select pairs for comparison in different ways).

The function you pass to sort is used to do that comparison. It calls the function and passes in the pair it is comparing as a and b.

It expects your function to return a negative number, a positive number or 0 to say which should be moved to be “first” (or 0 if they are “the same” and shouldn’t be moved).

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement