JavaScript sort()
JavaScript sort()
method is used to sort an array in ascending or descending order. It takes either no argument or a comparison function as an argument. This method modifies the original array and returns it sorted.
Syntax
array.sort(compareFunction)
- Parameter: Optional. A function that defines the sort order. If not specified, the array is sorted based on string Unicode point values, which means '9' is sorted before '80'.
- Return value: The sorted array in ascending order.
Example
const arr = [5, 1, 3, 2, 4];
// sort in ascending order
arr.sort();
console.log(arr); // Output: [1, 2, 3, 4, 5]
// sort in descending order
arr.sort((a, b) => b - a);
console.log(arr); // Output: [5, 4, 3, 2, 1]
Output
The sort()
method sorts the elements of the array in place. The original array is modified and the sorted array is returned as the result.