How to sort a map in JavaScript?


In JavaScript, Map is a type of data structure that stores the values in the form of key value pairs. It can store all types of data types, whether they are primitive or JavaScript objects. It stores the elements in the same order in which they are inserted, hence, when we iterate through its elements, it prints the elements in the same order as we have stored them.

As we have discussed that the order of elements stored in a Map is same as we insert elements in that Map. But, we can also sort the elements of the map in any order according to the value of different keys. We can use the custom sort() method of JavaScript to sort the Map elements according to the values of keys stored.

Syntax

Following syntax will show you how to create a map in JavaScript −

var map_name = new Map([...myMap].sort(cmp));

Here map_name is the sorted map, myMap is original map and cmp is comparison function used to compare two values in the map.

Steps

Follow the below-given steps to sort a map in JavaScript −

  • Step 1 − Define a map with some default values.

var myMap = new Map([
   [20, 8],
   [9, 5],
   [3, 9],
   [13, 0],
]);
  • Step 2 − Define a comparison function. This function is used to compare two elements.

function cmp(a, b) {
   return a[0] - b[0];
}
function cmp(a, b) {
   return a[0] - b[0];
}
  • Step 3− Create a new object sortedMap from the existing map myMap using Map() constructor. This steps contains three substeps −

  • Step 3.1 − First, the spread syntax […myMap] is used to create an array by spreading the element of map myMap into an array.

  • Step 3.2 − Next, the sort() function is called with comparison function, cmp.

  • Step 3.3 − In last the Map constructor is used to construct a new map sortedMap. The sortetMap contains sorted array.

sortedMap = new Map([...myMap].sort(cmp));
  • Step 4 − Display the sorted elements of map.

Let us now understand how we can sort a map in JavaScript with the help of code examples −

Example

The example below will explain to you how you can sort the map in ascending or the increasing order of value of keys in a map −

<html>
<body>
   <h2>Sorting keys in a map in JavaScript</h2>
   <p id = "prev">The initial order of values of keys in map is:</p>
   <p id = "result">The final sorted order of values of keys in map is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      var myMap = new Map([
         [20, 8],
         [9, 5],
         [3, 9],
         [13, 0],
      ]);

      for (var [key, value] of myMap) {
         prev.innerHTML += " <b> " + key + " </b> ";
      }

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

      sortedMap = new Map([...myMap].sort(cmp));

      for (var [key, value] of sortedMap) {
         result.innerHTML += " <b> " + key + " </b> ";
      }
   </script>
</body>
</html>

In the above example, we have used the sort() method in such a way that it sorts the elements in ascending or increasing order with the help of that cmp function that we used to define the order of the elements in which they have to be sorted.

Let us now discuss one more code example in which we will sort the elements of the map in descending or the decreasing order.

Approach

The approach of this example and the previous example is almost, you just need to perform some minor changes. The change you have to perform in the previous algorithm is that change the order of returning values in cmp function from a[0] – b[0] to b[0] - a[0]. By changing this value it will sort the elements in the decreacing or the descending order.

Example

The below example will illustrates how we can sort the values of key elements of a map in decreasing order −

<html>
<body>
   <h2>Sorting a map in JavaScript</h2>
   <p>Enter any two numbers:</p>
   <input type = "number" id = "inp1"> <br> <br>
   <input type = "number" id = "inp2"> <br> <br>
   <button id = "btn" onclick = "mapSort()"> click to sort </button>
   <p id = "prev">The initial order of values of keys in map is:</p>
   <p id = "result">The final sorted order of values of keys in map is:</p>
   <script>
      var result = document.getElementById("result");
      var prev = document.getElementById("prev");
      function mapSort() {
         var myMap = new Map([
            [20, 8],
            [9, 5],
            [3, 9],
         ]);
         var inp1 = document.getElementById("inp1");
         var inp2 = document.getElementById("inp2");
         var val1 = inp1.value;
         var val2 = inp2.value;
         var num1 = Number(val1);
         var num2 = Number(val2);
         myMap.set(num1, num2);

         for (var [key, value] of myMap) {
            prev.innerHTML += " <b> " + key + " </b> ";
         }

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

         myMap = new Map([...myMap].sort(cmp));

         for (var [key, value] of myMap) {
            result.innerHTML += " <b> " + key + " </b> ";
         }
      }
   </script>
</body>
</html>

In the above example, we have sorted the values of key elements stored in a map in decreasing or descending order by passing the cmp function to the sort() method in such a way that it resturn the larger values first and then the smaller values to sort the map.

Conclusion

In this article, we have learned about sorting the map in JavaScript with the help of sort() method. We have implemented it practically and sorted a map in decreasing and increasing order.

Updated on: 20-Nov-2023

136 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements