How to use the Array sort method

JavaScript polyfill, by , Saturday, March 8th, 2014

The build in Array.prototype.sort() method is there to help you sort information in arrays by applying a sort function to each element in the array. The syntax is like this;

  1. arr.sort([compareFunction]);

Where arr is the given array to sort, and [compareFunction] is a function passed in to apply to each element in the array. The simplest example is sorting an array of numbers ascending; (see also How to sort an array numerically)

  1. var num = [729, 81, 6561, 9],
  2. orderedNum = num.sort(function (a, b) {
  3. return a - b;
  4. });
  5. // Prints out [9, 81, 729, 6561]
  6. console.log(orderedNum);

The way this works is, that the sort() method is fed a sort function which result is used to decide what to do with each element in the array. When done, it returns a new array with the changes applied. If we call the two relative values that are being compared a and b respectively, the rules are as follows;

  1. If the compare function returns a number less than 0, a will be sorted to a lower index than b, i.e. a comes before b in the returned array.
  2. If the compare function return 0, the relative position of a and b is left unchanged, with respect to each other. This does not mean how ever, that they are left at the current position, as they are still sorted with respect to all other elements in the array.
  3. If the compare function returns a number greater than 0, b is sorted to a lower index than a.

As I am sure you can imagine, there are almost endless uses for this method, and surely you will encounter situations where it is useful in your development.