Sort alphabetically
// Define an array
var animals = ["Tiger", "Giraffe", "Lion", "Elephant"];
// Sort it
animals.sort();
The new array will now be ['Elephant', 'Giraffe', 'Lion', 'Tiger'].
Reversed alphabetically
But what if you want to sort it in the reversed order? If you just run ".reverse()" on the array, it will just be reversed and not by letter. To fix this, we need to run ".sort()" first.
// Define an array
var animals = ["Tiger", "Giraffe", "Lion", "Elephant"];
// Sort it
animals.sort();
animals.reverse();
The new array will now be ['Tiger', 'Lion', 'Giraffe', 'Elephant'].
Sort numerically
Sorting an array based on the numerical value is a little bit more tricky.
// Define an array
var numbers = [10, 4, 13, 1, 100];
// Sort it
numbers.sort(function(a, b) {return a - b});
As you can see, we still use the .sort() function from JavaScript, but we pass in a function as a parameter.
The new array will now be: [1, 4, 10, 13, 100].