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:

  1. Convert Set to Array using spread operator or Array.from()
  2. Sort the array using sort()
  3. 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 - b for ascending numeric sort
  • Use (a, b) => b - a for 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.

Updated on: 2026-03-15T23:19:01+05:30

573 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements