JavaScript Array sort() method sorts the elements of an array either by the default sorting order or using a custom sorting function. By default, it sorts the array elements as strings in ascending order based on their string Unicode values.
Syntax
array.sort(compareFunction)
Parameters
compareFunction(optional): The function defines an alternative sort order, and it should return a negative, zero, or positive value, depending on the arguments.
Return value
Returns the array after sorting the elements of the array in place (meaning that it modifies the original array).
Visual Representation
Example 1: How to Use Array Sort () Method
let days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"];
days.sort();
console.log(days);
//Without Compare Function
let numbers = [3,56,789,22,234];
numbers.sort();
console.log(numbers);
Output
[ 'Friday', 'Monday', 'Thursday', 'Tuesday', 'Wednesday' ]
[ 22, 234, 3, 56, 789 ]
In the first use case, we used the sort() without providing a compare function. The elements of the days array are converted to strings and sorted in ascending alphabetical order. So ‘Friday‘ comes before ‘Monday’, ‘Thursday’, ‘Tuesday’, and ‘Wednesday’.
In the second use case, the numbers aren’t sorted numerically. Instead, they are sorted based on their string representation, resulting in a non-intuitive order. To sort them numerically, we need to provide a compare function.
Example 2: Custom Sort Function
let numbers = [3,56,789,22,234];
numbers.sort((a, b) => a - b);
console.log(numbers);
Here we are sorting the values in Ascending order.
Output
[ 3, 22, 56, 234, 789 ]
We can do the Descending order also.
let numbers = [3,56,789,22,234];
numbers.sort((a, b) => b - a);
console.log(numbers);
Output
[ 789, 234, 56, 22, 3 ]
How does the compare function work?
The compare() function in the sort() method helps determine the order in which elements should be arranged. It takes two arguments, typically referred to as a and b.
Here’s the syntax for the compareFunction :
function compareFunction(a, b)
{
// return a value based on comparison
}
- If returns a value < 0, a will be sorted to an index lower than the element b (a comes before b)
- If returns a value > 0, a will be sorted to an index higher than the element a (b comes before a)
- If returns a value == 0, a and b will remain unchanged
Example 3: Sorting an array of objects
let apps = [
{ name: 'Amazon', value: 1 },
{ name: 'Amazon Prime', value: 21 },
{ name: 'Amazon Music', value: 10 },
{ name: 'Amazon Go', value: 100 },
{ name: 'Amazon Alexa', value: 13 }
];
apps.sort((a, b) => a.value-b.value);
console.log(apps);
Here, we have used the arrow function. Now, it will sort the Ascending order based on the values.
Output
[
{ name: 'Amazon', value: 1 },
{ name: 'Amazon Music', value: 10 },
{ name: 'Amazon Alexa', value: 13 },
{ name: 'Amazon Prime', value: 21 },
{ name: 'Amazon Go', value: 100 }
]
Example 4: Sorting non-ASCII characters and localeCompare()
For sorting strings with non-ASCII characters, i.e., strings with accented characters like these (e, é, è, a, ä, etc.),
To correctly sort strings with non-ASCII characters, you can use the String.localCompare() method inside the sort() function.
let words = ['Åland', 'premier', 'cliché', 'communiqué', 'café', 'adieu'];
words.sort(function (a, b) {
return a.localeCompare(b);
});
console.log(words);
Output
[ 'adieu', 'Åland', 'café', 'cliché', 'communiqué', 'premier' ]
Example 5: Sorting an Array in random order
We can use the Math.random() function to get the random results.
let numbers = [3,56,789,22,234];
numbers.sort(() => 0.5 - Math.random());
console.log(numbers);
Output
[ 56, 3, 789, 22, 234 ]
Example 6: Sorting the array of objects by a specified property
let players = [
{ name: 'Ronaldo', salary: 90000, age: 37 },
{ name: 'Messi', salary: 84000, age: 34 },
{ name: 'Neymar', salary: 79000, age: 31 }
];
players.sort((x, y) => x.salary - y.salary);
console.log(players)
Output
[
{ name: 'Neymar', salary: 79000, age: 31 },
{ name: 'Messi', salary: 84000, age: 34 },
{ name: 'Ronaldo', salary: 90000, age: 37 }
]