array.sort()

Overview

array.sort( [compareFunction] ) sorts an array in place – mutating the array. There is no return value.

The compareFunction is a function that is used by sort to evaluate sibling values in turn, and sort in the appropriate order.

Compare Function Setup

function compare(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}

Sample Compare Function

function compareNumbers(a, b) {
  return a - b;
}

In actual code …

function compareNumbers(a, b) {
  return a - b;
}

let array = [1,6,4,2,8,11,4,99,129];
array.sort(compareNumbers);

// Or all in line:
array.sort( (a,b) => { 
  return a-b; 
});

Caveats and Notes

Reference