Sort Elements of Array in JavaScript
In JavaScript, Array.sort() method is used to sort the elements in the array in ascending order, based on the values, or based on an optional compare function.
Syntax
array.sort()
array.sort(compareFunction)
array
is an array which should be sorted.sort
is the array method name.- compareFunction is a function that takes two parameters and returns a value.
sort()
method sorts the elements of the given array
in ascending order. If compareFunction
is provided, then the elements of the array
are sorted based on the values returned by the compareFunction
for each element of the array.
To sort an array in descending order, reverse the array after sorting.
sort()
method modifies the original array. Therefore, care must be takes if original array has to be preserved.
Examples
1. Sort array of numbers in ascending order.
let numbers = [5, 1, 7, 3, 2, 0];
numbers.sort();
console.log(numbers);
2. Sort array of strings lexicographically in ascending order.
let fruits = ['cherry', 'apple', 'banana'];
fruits.sort();
console.log(fruits);
3. Sort array of strings based on length, in ascending order.
function stringLength(str1, str2) {
return str1.length - str2.length;
}
let names = ['Anita', 'Amy', 'America', 'Alba'];
names.sort(stringLength);
console.log(names);
4. Sort array in descending order.
let numbers = [5, 1, 7, 3, 2, 0];
numbers.sort();
numbers.reverse();
console.log(numbers);