Skip to content
Related Articles

Related Articles

How to sort a map in JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 11 Mar, 2022

Map in JavaScript is a special kind of object that stores elements in terms of [key, value] pair. The map can store both primitive as well as objects. When iterating over the map object, it returns the [key, value] pair in the same order as inserted.

In this article, we will see how to sort the Map according to the value of the keys.  One way to achieve this goal is to use the in-built sort() function available in JavaScript on the multi-dimensional Array created with the help of the array destructuring of the object generated by the Map.entries() method. 

Syntax:

[...map1.entries()] 
# this will generate a multi-dimensional array 
# out of the key-value pairs stored in the map

Now we shall sort this array in increasing order using the sort function, by default it will sort the array according to the increasing values of the first elements stored in the arrays.

[...map1.entries()].sort()

Let’s understand using examples.

Example 1: In this example, we are sorting the map by the increasing values of keys.

Javascript




<script>
    // Initializing and inserting values into Map
    let map1 = new Map([
      [4, 2],
      [2, 3],
    ]);
     
    // Inserting new element into map using set() method
    map1.set(3, 10);
    document.write("Our map :", "</br>");
    document.write(map1, "</br>");
     
    // Adding the sorting logic
    map1 = new Map([...map1.entries()].sort());
     
    // Separately printing only keys
    for (let [key, value] of map1) {
      document.write(key, " ");
    }
</script>

Output:

Our map :
Map(3) { 4 => 2, 2 => 3, 3 => 10 }
2 3 4

Example 2: In this example, we are sorting the map by the decreasing values of keys.

Javascript




<script>
    let map1 = new Map([
      [4, 2],
      [2, 3],
    ]);
     
    // Inserting new element into map using set() method
    map1.set(3, 10);
    document.write("Our map :", "</br>");
    document.write(map1, "</br>");
     
    // Adding the custom sorting logic to sort
    // by decreasing values of keys
    map1 = new Map([...map1.entries()].sort((a, b) => b[0] - a[0]));
     
    // Separately printing only keys
    for (let [key, value] of map1) {
      document.write(key, " ");
    }
</script>

Output:

Our map :
Map(3) { 4 => 2, 2 => 3, 3 => 10 }
4 3 2

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!