Notes

Array.sort() - Sorting Arrays in JavaScript

Edit on GitHub

JavaScript

The method for sorting arrays is called.. sort!.

Examples

Default sort

 1var fruit = ['cherries', 'apples', 'bananas'];
 2fruit.sort(); // ['apples', 'bananas', 'cherries']
 3
 4var scores = [1, 10, 21, 2]; 
 5scores.sort(); // [1, 10, 2, 21]
 6// Watch out that 10 comes before 2,
 7// because '10' comes before '2' in Unicode code point order.
 8
 9var things = ['word', 'Word', '1 Word', '2 Words'];
10things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
11// In Unicode, numbers come before upper case letters,
12// which come before lower case letters.

Notes

  • Sorts elements in place
  • The default sort order is according to string Unicode code points
  • You can use sort to sort both objects and arrays (because: arrays are objects..)
  • If you are passing object properties as parameters to your (separately defined) sort function, use bracket notation to access the parameter (variable). obj[param] instead of obj.param or obj['param'].

Related