JavaScript Array Sorting Methods
Sorting is the process of arranging array elements in a specific order. JavaScript provides built-in methods to sort arrays alphabetically or numerically. You can also reverse the order or create your own custom sorting logic.
Sorting is useful when displaying products by price, arranging names alphabetically, or ordering marks from highest to lowest.
sort()
The sort() method sorts the elements of an array.
By default, it sorts values as strings in ascending order.
Syntax
arrayName.sort();
Example
let fruits = ["Mango", "Apple", "Orange", "Banana"];
fruits.sort();
console.log(fruits);Output
[“Apple”, “Banana”, “Mango”, “Orange”]
Sorting Numbers
When sorting numbers, use a compare function. Otherwise, numbers are sorted as strings.
Incorrect Example
let numbers = [100, 25, 8, 50];
numbers.sort();
console.log(numbers);Output
[100, 25, 50, 8]
Correct Example
let numbers = [100, 25, 8, 50];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);Output
[8, 25, 50, 100]
reverse()
The reverse() method reverses the order of the array.
Syntax
arrayName.reverse();
Example
let fruits = ["Apple", "Banana", "Mango"];
fruits.reverse();
console.log(fruits);Output
[“Mango”, “Banana”, “Apple”]
toSorted()
The toSorted() method returns a new sorted array without changing the original array.
Syntax
arrayName.toSorted();
Example
let fruits = ["Mango", "Apple", "Orange"];
let sorted = fruits.toSorted();
console.log(sorted);
console.log(fruits);Output
[“Apple”, “Mango”, “Orange”]
[“Mango”, “Apple”, “Orange”]
toReversed()
The toReversed() method returns a new reversed array without modifying the original array.
Example
let numbers = [10, 20, 30];
let result = numbers.toReversed();
console.log(result);
console.log(numbers);Output
[30, 20, 10]
[10, 20, 30]
Comparison of Methods
| Method | Changes Original Array | Returns New Array |
| sort() | Yes | No |
| reverse() | Yes | No |
| toSorted() | No | Yes |
| toReversed() | No | Yes |