How to sort an array numerically

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

Using the build in sort() method and giving it a compare function, sorting an array of numbers ascending is easy;

  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);

Doing the same thing, but just descending is trivial, as we just need to switch a and b around;

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

To better understand why this works, take a look at How to use the Array sort method