Wednesday, July 20, 2011

The function parameter for javascript Array.Sort

I guess If you are reading this you already know that javascript's Array.sort function can take a function parameter.

Did yo ever wander what exactly should this function return ?

well its simple:
This function (which should take two elements from your array) f(e1,e2) should return:
  • any negative number to indicate that its first parameter should appear before (have a smaller index) the second parameter in the sorted array .
  • zero if you are indifferent to the order in which those two elements will appear in the sorted Array
  • any positive number to indicate that its first parameter should appear after (have a larger index) the second parameter in the sorted array .
Using this info you could even sort mixed type arrays and do multilevel sorting (e.g. sort by date and alphabetically within the date).


 
Clicky Web Analytics