How to useMap.entries() and sort() Method in Javascript

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

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

Javascript
// 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);
console.log("Our map :");
console.log(map1);

// Adding the sorting logic
map1 = new Map([...map1.entries()].sort());

// Separately printing only keys
for (let [key, value] of map1) {
    console.log(key, " ");
}

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
let map1 = new Map([
    [4, 2],
    [2, 3],
]);

// Inserting new element into map using set() method
map1.set(3, 10);
console.log("Our map :");
console.log(map1);

// 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) {
    console.log(key, " ");
}

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


How to sort a map in JavaScript ?

We will see how to sort the Map according to the value of the keys.  

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.

Below are the following approaches:

Table of Content

  • Using Map.entries() and sort() Method
  • Using Array.from() and sort() Method

Similar Reads

Approach 1: Using Map.entries() and sort() Method

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....

Approach 2: Using Array.from() and sort() Method

In this method, we will use Array.from() which is used to convert the map into an array, and then by using the sort() function we will sort the map. In this method, we will sort the map by values....

Approach 3: Using the Lodash Library

Lodash is a popular JavaScript utility library that provides a variety of functions for common programming tasks, including sorting data structures like Maps. By leveraging the sortBy() function from Lodash, we can easily sort a Map based on either keys or values....