Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort a set in JavaScript?
A Set is a JavaScript data structure that stores unique values in insertion order. Unlike arrays, Sets cannot be sorted directly because they don't have a sort() method. To sort a Set, we must convert it to an array, sort the array, and create a new Set from the sorted results.
In this article, we'll learn different approaches to sort Sets in JavaScript using array conversion and the sort() method.
Why Sets Cannot Be Sorted Directly
Sets maintain insertion order and focus on uniqueness rather than sorting. They lack array methods like sort(), so we need an indirect approach.
Approach: Convert to Array, Sort, Convert Back
The standard approach involves three steps:
- Convert Set to Array using spread operator or
Array.from() - Sort the array using
sort() - Create a new Set from the sorted array
Method 1: Ascending Order (Default)
<script>
let mySet = new Set([5, 2, 8, 1, 9, 3]);
console.log("Original Set:", mySet);
// Convert to array, sort, convert back
let sortedArray = [...mySet].sort((a, b) => a - b);
let sortedSet = new Set(sortedArray);
console.log("Sorted Set (ascending):", sortedSet);
// Display as arrays for clarity
console.log("Original order:", [...mySet]);
console.log("Sorted order:", [...sortedSet]);
</script>
Method 2: Descending Order
<script>
let numberSet = new Set([10, 3, 7, 1, 9, 5]);
console.log("Original Set:", [...numberSet]);
// Sort in descending order
let descendingArray = Array.from(numberSet).sort((a, b) => b - a);
let descendingSet = new Set(descendingArray);
console.log("Sorted Set (descending):", [...descendingSet]);
</script>
Method 3: Sorting String Sets
<script>
let fruitSet = new Set(["banana", "apple", "cherry", "date"]);
console.log("Original fruits:", [...fruitSet]);
// Sort strings alphabetically
let sortedFruits = [...fruitSet].sort();
let sortedFruitSet = new Set(sortedFruits);
console.log("Sorted fruits:", [...sortedFruitSet]);
</script>
Interactive Example
<!DOCTYPE html>
<html>
<body>
<h2>Sort a Set in JavaScript</h2>
<p>Enter numbers to add to the set:</p>
<input type="number" id="numberInput">
<button onclick="addToSet()">Add Number</button>
<button onclick="sortAscending()">Sort Ascending</button>
<button onclick="sortDescending()">Sort Descending</button>
<button onclick="clearSet()">Clear Set</button>
<p id="currentSet">Current Set: []</p>
<p id="sortedResult"></p>
<script>
let mySet = new Set();
function addToSet() {
let input = document.getElementById("numberInput");
let value = parseInt(input.value);
if (!isNaN(value)) {
mySet.add(value);
updateDisplay();
input.value = "";
}
}
function sortAscending() {
let sortedArray = [...mySet].sort((a, b) => a - b);
let sortedSet = new Set(sortedArray);
document.getElementById("sortedResult").innerHTML =
"Sorted Ascending: [" + [...sortedSet].join(", ") + "]";
}
function sortDescending() {
let sortedArray = [...mySet].sort((a, b) => b - a);
let sortedSet = new Set(sortedArray);
document.getElementById("sortedResult").innerHTML =
"Sorted Descending: [" + [...sortedSet].join(", ") + "]";
}
function clearSet() {
mySet.clear();
updateDisplay();
document.getElementById("sortedResult").innerHTML = "";
}
function updateDisplay() {
document.getElementById("currentSet").innerHTML =
"Current Set: [" + [...mySet].join(", ") + "]";
}
</script>
</body>
</html>
Comparison of Approaches
| Method | Syntax | Best For |
|---|---|---|
| Spread operator | [...set].sort() |
Modern JavaScript, readable |
| Array.from() | Array.from(set).sort() |
Better browser compatibility |
| Custom comparator | [...set].sort((a,b) => b-a) |
Complex sorting logic |
Key Points
- Sets don't have a native
sort()method - Always convert to array first, then sort, then back to Set
- Use
(a, b) => a - bfor ascending numeric sort - Use
(a, b) => b - afor descending numeric sort - String sorting works with default
sort()method
Conclusion
Sorting Sets in JavaScript requires converting them to arrays first. Use the spread operator [...set] or Array.from() for conversion, apply sort() with appropriate comparators, then create a new Set from the sorted array.
