8

Possible Duplicate:
How does Javascript's sort() work?

var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return b - a})//  for descending order

In a callback function, what does a and b variables refer to?? why and how does b-a exactly make array in descending order??

Community
  • 1
  • 1
DrStrangeLove
  • 11,227
  • 16
  • 59
  • 72

3 Answers3

7

a and b are two of the values in the array, that you compare so Javascript can sort them.

The function is called lots of times to determine where each element in the array is compared to all the others. The exact number of times the function is called depends on the number of elements in the array and their original order.

You need to return 0 if the two elements are equal, a negative number if a should be before b and a positive number if b should be before a.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
2

The sort function has internal sorting algorithm. You just provide a way for the algorithm to determine, given two members of the array, which one of them is greater ( that is the purpose of the b-a. ) Using this, the algorithm will be able to place the elements in the necessary order.

manojlds
  • 290,304
  • 63
  • 469
  • 417
-1

Passing no parameters will specify ascending lexicographical order (alphabetical).

However, you also have the option of passing in a function which array.sort will use to sort your array. The function you pass in is supposed to compare exactly two elements with each other, and the array.sort function will use your function in order to sort the entire array efficiently. Your function is simply supposed to compare the two values.

Your function should return a negative number if a comes before b, 0 if a is equal to b, and a positive number if a comes after b. Therefore return b - a will work for descending order because whenever b - a is positive, b is larger, and therefore will come before a, thus "descending". Similar for negative and equivalent values.

Andrew Rasmussen
  • 14,912
  • 10
  • 45
  • 81
  • Not true. Passing no comparator specifies ascending order as by comparing the string value lexically. Calling that ascending order in the context of sorting arrays of numbers is misleading. `a = [1, 2, 10]; a.sort()` leaves a with `[1, 10, 2]`. – Mike Samuel Jul 09 '11 at 23:18