Array.sort() - Sorting Arrays in JavaScript
The method for sorting arrays is called.. sort
!.
Examples
Default sort
var fruit = ['cherries', 'apples', 'bananas'];
fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
// Watch out that 10 comes before 2,
// because '10' comes before '2' in Unicode code point order.
var things = ['word', 'Word', '1 Word', '2 Words'];
things.sort(); // ['1 Word', '2 Words', 'Word', 'word']
// In Unicode, numbers come before upper case letters,
// 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 ofobj.param
orobj['param']
.