This tutorial will show you how to sort arrays in the JavaScript programming language with the array sort() method and provide some code examples.
What is an Array in JavaScript?
An array is a type of JavaScript variable that can hold a series of variables, references to variables, or values.
It’s like a list of items. Each item or element in the array has a value and a position. The position is the order the element appears in the array and is called the index. Indexes are zero-indexed – meaning that they start counting at position 0 – so the first element in an array is at index 0, the second item is at index 1, and so on.
In JavaScript, an array is constructed using square brackets ([]) to contain a comma-separated list of array values:
var myArray = ['dog', 'cat', 'pig', 'parrot'];
The array sort() Method
The values in an array can be re-ordered (changing the order they appear in, and their index). The sort() method can be used to re-order the elements in an array based on a function which compares the values in it.
JavaScript Array sort() Method Syntax
The JavaScript syntax for the array sort() method is as follows:
array.sort(COMPARE_FUNCTION)
Note that:
- array can be any array type variable
- COMPARE_FUNCTION is an optional comparison function
- If it is not supplied, the elements in the array will be sorted by their string value
- The COMPARE_FUNCTION should accept two parameters – the two elements which are to be compared to define the sort
- The COMPARE_FUNCTION will then be run on each array element and the element following it to sort the array
- array will be sorted in place – the original array will be modified and the elements in it sorted rather than a duplicate sorted array being returned
Array Sort Examples
If no comparison function is passed to the sort() method, the values in it will be converted to strings and sorted by their UNICODE value – in effect, sorting alphabetically in ascending order:
var myArray = ['dog', 'cat', 'pig', 'parrot']; myArray.sort(); console.log(myArray);
The array will now contain the sorted values:
["cat", "dog", "parrot", "pig"]
Sorting this way can also be done in descending order by simply reversing the sorted array:
var myArray = ['dog', 'cat', 'pig', 'parrot']; myArray.sort(); myArray.reverse(); console.log(myArray);
The array will now contain:
["pig", "parrot", "dog", "cat"]
Array Sort with Comparison Function Examples
Comparison functions can be used to sort arrays based on your own criteria.
Comparing Numbers
The below code will use a comparison function to sort numbers in ascending order.
var myNumbers = [1, 5, 2, 3, 6, 10]; myNumbers.sort(function(value1, value2) { return value1 - value2; }); console.log(myNumbers);
This is a simple example of how the comparison function works. The result of value1 – value2 will be negative if value2 is greater than value1, or 0 if they are equal, and otherwise positive. Thus, the values in the array can be sorted based on whether the return value of the sort value is positive, negative, or zero.
Comparing Objects (and Other Values)
Comparisons can take any form so long as the returned value can be parsed as a positive, negative, or zero numerical value. This lets you write your own comparison logic to suite your usage scenario.
Below, an array of objects is defined which contains a list of pets – their name, what animal they are, and their age.
The array is then sorted using a sort function which compares the age within each object – UNLESS it’s Moe the fish. He’ll always come first in the sorted array according to the sort logic:
var myPets = [ { name: 'Shemp', animal: "dog", age: 4 }, { name: 'Larry', animal: "cat", age: 1 }, { name: 'Moe', animal: "fish", age: 6 }, { name: 'Curly', animal: "parrot", age: 5 } ]; myPets.sort(function(value1, value2) { if(value2.name === 'Moe') return 1; return value1.age - value2.age; }); console.log(myPets);
Randomising JavaScript Arrays
Arrays can also be randomised – we cover that in a separate article here.