How to sort a set in JavaScript?


A set is also a data structure that is almost similar to the map data structure. The only difference between them is that map stores the elements in the form of key-value pair, while set does not it only stores a single value in the same order as it was inserted. It can also store primitive data types as well as objects as map does.

A set contains all the elements in the same order as they are inserted. But, we can sort a set in any order whether in increasing or decreasing order of elements using the sort() method of JavaScript, which we generally used to sort arrays in a particular order.

In this article, we are going to learn how we can use the sort() method to sort a set in JavaScript.

Let us first see how we can create a set in JavaScript.

Syntax

Follow the below syntax to create a set in JavaScript −

var set_name = new Set();

We can use the add() method of set to insert or add new elements to the set.

Steps

  • Step 1− In the first step, we will add an input element to the document to get the input elements one by one from user.

  • Step 2− In the next step, we will add three button elements with onclick event associated with each of them. The first button will add the entered element to the set, second button will clear all the elements from the set and third button will sort the elements of the set and display the previous as well as the sorted order of the elements.

  • Step 3− In the third step, we will define three different functions with different functionalities and assign them to the onclick events of the buttons defined in the previous step according to their functionality.

  • Step 4− In the last step, we will write the code of all three functions defined in the last step to add, clear and sort the elements of the set in JavaScript.

Let us practically implement the sort() method to sort the elements of an set in a particular order.

Example

The example below will explain you how to use the sort() method to sort the elements of a set in the increasing or the ascending order −

<!DOCTYPE html>
<html>
<body>
   <h2>Sorting a set in JavaScript</h2>
   <p>Enter a number to insert into set:</p>
   <input type = "number" id = "inp1"><br><br>
   <button id = "add" onclick = "setAdd()"> Add Item to set</button>
   <button id = "clear" onclick = "clearSet()"> Clear the set</button>
   <button id = "btn" onclick = "setSort()">click to sort</button>
   <p id = "prev">The initial order of values in set is:</p>
   <p id = "result">The final sorted order of values in set is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var mySet = new Set();

      function setAdd() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var num1 = Number(val1);
         mySet.add(num1);
         inp1.value = " ";
      }

      function clearSet() {
         mySet.clear();
      }

      function setSort() {
         var tempArr = [];

         for (var item of mySet) {
            tempArr.push(item);
         }

         tempArr.sort();

         for (var item of mySet) {
            prev.innerHTML += " <b> " + item + " </b> ";
         }

         mySet.clear();

         for (var item of tempArr) {
            mySet.add(item);
         }

         for (var item of mySet) {
            result.innerHTML += " <b> " + item + " </b> ";
         }
      }
   </script>
</body>
</html>

In the above example, we have used the sort() method to sort the elements of a set in ascending or the increasing order with the help of a array as we discussed in the approach to solve this problem.

Let us see one more code example in which we will sort the elements of the set in decreasing or the descending order.

Approach

The approach of the previous and this example is same. You just need to write a cmp function and pass it to the sort() method to make it sort the items in the given order. The cmp function is explained by the below code example, where we will use it to sort the items in decreasing or the descending order.

Example

The example below will illustrate how to use the sort() method with a cmp function to define the order of sorting −

<!DOCTYPE html>
<html>
<body>
   <h2>Sort a set in JavaScript</h2>
   <p>Enter a number to insert into set:</p>
   <input type = "number" id = "inp1"> <br> <br>
   <button id = "add" onclick = "setAdd()">Add Item to set</button>
   <button id = "clear" onclick = "clearSet()">Clear the set</button>
   <button id = "btn" onclick = "setSort()">click to sort</button>
   <p id = "prev">The initial order of values in set is:</p>
   <p id = "result">The final sorted order of values in set is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var mySet = new Set();
      function setAdd() {
         var inp1 = document.getElementById("inp1");
         var val1 = inp1.value;
         var num1 = Number(val1);
         mySet.add(num1);
         inp1.value = " ";
      }

      function clearSet() {
         mySet.clear();
      }

      function setSort() {
         var tempArr = [];

         for (var item of mySet) {
            tempArr.push(item);
         }

         function cmp(a, b) {
            return b - a;
         }

         tempArr.sort(cmp);

         for (var item of mySet) {
            prev.innerHTML += " <b> " + item + " </b> ";
         }

         mySet.clear();

         for (var item of tempArr) {
            mySet.add(item);
         }

         for (var item of mySet) {
            result.innerHTML += " <b> " + item + " </b> ";
         }
      }
   </script>
</body>
</html>

In this example, we have used the sort() method to sort the elements of a set in decreasing or the descending order by specifying the order of sorting with the help of the cmp function.

Conclusion

In this article, we have learned about the different ways of using the sort() method in JavaScript to sort the items of a set in different orders. We have also seen two different JavaScript code examples, where, in the first one we sort the items in the ascending or the increasing order, while in the second example, we sorted the elements in the decreasing or the descending order by giving the sort() method order for sorting using the cmp function.

Updated on: 20-Nov-2023

114 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements