In JavaScript, you can sort an array using the sort() method. The sort() method sorts the elements of an array in place and returns the sorted array.
Here's an example of how to sort an array of numbers in ascending order:
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 3, 4, 5]
In this example, the sort() method takes a callback function as an argument, which compares two elements of the array at a time. The callback function subtracts b from a, which sorts the elements in ascending order.
To sort an array of strings in alphabetical order, you can use the same sort() method and pass a different callback function:
const fruits = ['banana', 'apple', 'orange', 'pineapple', 'grape'];
fruits.sort((a, b) => a.localeCompare(b));
console.log(fruits); // ['apple', 'banana', 'grape', 'orange', 'pineapple']
In this example, the sort() method uses the localeCompare() method to compare two strings at a time and sort them in alphabetical order.
You can also use the reverse() method to sort an array in descending order:
const numbers = [4, 2, 5, 1, 3];
numbers.sort((a, b) => b - a);
console.log(numbers); // [5, 4, 3, 2, 1]
In this example, the callback function subtracts a from b, which sorts the elements in descending order.
array.sort() method
The sort() method of the array in JavaScript sorts the elements of an array. The sort order can be either alphabetic or numeric and either ascending or descending. By default, the sort() method sorts the values as strings in alphabetical and ascending order.
array.sort();
array.reverse() method
The reverse() method of the array in JavaScript reverses the elements in an array.
array.reverse();
Example of sorting a JavaScript array
Copy the HTML code and paste it into your file. The name extension must be .html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Reverse an Array in Javascript</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
<div>
<p>Actual Array :<span id="actual"></span></p>
<p>Reversed Array :<span id="reverse"></span></p>
<p>Ascending order Sort Array :<span id="asc"></span></p>
<p>Descending order Sort Array :<span id="desc"></span></p>
</div>
<button onclick="sort()">Sort</button>
<button onclick="rev()">Reverse</button>
<button onclick="desc()">Descending Order</button>
<script type="text/javascript">
var names=["Jack","Kim","Joe","Suzie","Alex"];
document.getElementById("actual").innerHTML =names;
function rev(){
document.getElementById("reverse").innerHTML =names.reverse();
}
function sort(){
names.sort();
document.getElementById("asc").innerHTML =names;
}
function desc(){
names.reverse();
document.getElementById("desc").innerHTML =names;
}
</script>
</body>
</html>
Output
Reverse in Descending Order
Summary
In this blog, I explained Javascript array methods and how to sort a JavaScript array.