JavaScript Array Sort
Sorting arrays helps you organize data alphabetically, numerically, or by custom criteria. JavaScript provides sort()
and reverse()
to rearrange elements, and you can customize the sorting order with compare functions.
Key Topics
Basic sort()
sort()
sorts elements as strings by default, which can lead to unexpected results with numbers.
let letters = ["C", "A", "B"];
letters.sort();
console.log(letters);
Output
> ["A", "B", "C"]
Explanation: Sorting letters alphabetically works as expected. "C", "A", "B" becomes "A", "B", "C".
Numeric Sorting
For numbers, use a compare function to ensure correct numeric order.
let nums = [10, 2, 5, 1];
nums.sort((a, b) => a - b);
console.log(nums);
Output
> [1, 2, 5, 10]
Explanation: The compare function (a, b) => a - b
ensures numbers are sorted in ascending order. Without it, sort()
treats them as strings.
reverse()
reverse()
reverses the order of elements in an array, which can be used after sorting to achieve descending order.
nums.reverse();
console.log(nums);
Output
> [10, 5, 2, 1]
Explanation: After sorting in ascending order, reversing the array produces a descending order.
JavaScript Usage in DOM
This DOM-based example sorts and displays an array of items on a webpage, demonstrating dynamic sorting capabilities.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Sort in DOM</title>
</head>
<body>
<h1>Array Sort Demo</h1>
<button onclick="sortItems()">Sort Items</button>
<p id="output"></p>
<script>
let items = ["Banana", "Apple", "Cherry"];
function sortItems() {
items.sort();
document.getElementById("output").textContent = items.join(", ");
}
</script>
</body>
</html>
Key Takeaways
- sort(): Sorts arrays alphabetically by default.
- Numeric Sort: Use a compare function for correct numerical order.
- reverse(): Reverses the order of elements.
- DOM Integration: Dynamically sort and display arrays on webpages.