The sort() method of the Array class in JavaScript sorts the elements of an array in place and returns the sorted array.
There are 2 variations for the syntax of Array.sort() method. They are:
sort()
This method sorts the elements of an array in place in ascending, UTF-16 code unit order.
Returns value of type Array
.
sort(compareFn)
Parameters
Parameter | Optional/Required | Description |
---|---|---|
compareFn | optional | A function that defines the sort order. It takes two arguments: a and b. If compareFn(a, b) is less than 0, a comes before b. If compareFn(a, b) is greater than 0, a comes after b. If compareFn(a, b) is equal to 0, the order remains unchanged. |
This method sorts the elements of an array in place according to the compare function.
Returns value of type Array
.
In JavaScript, we can use the sort() method to sort an array of numbers in ascending order.
For example,
const arr = [5, 3, 8, 1, 2];
const sortedArr = arr.sort();
console.log(sortedArr);
[1, 2, 3, 5, 8]
We can use the sort() method to sort an array of strings in alphabetical order.
For example,
const strArr = ['banana', 'apple', 'cherry', 'date'];
const sortedStrArr = strArr.sort();
console.log(sortedStrArr);
['apple', 'banana', 'cherry', 'date']
We can use the sort() method with a compare function to sort an array of numbers in descending order.
For example,
const arr = [5, 3, 8, 1, 2];
const compareNumbers = (a, b) => b - a;
const sortedArr = arr.sort(compareNumbers);
console.log(sortedArr);
[8, 5, 3, 2, 1]
In this JavaScript tutorial, we learned about sort() method of Array: the syntax and few working examples with output and detailed explanation for each example.