How to sort a map in JavaScript ?
Last Updated :
22 Dec, 2023
In this article, 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:
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.
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
let map1 = new Map([
[4, 2],
[2, 3],
]);
map1.set(3, 10);
console.log( "Our map :" );
console.log(map1);
map1 = new Map([...map1.entries()].sort());
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],
]);
map1.set(3, 10);
console.log( "Our map :" );
console.log(map1);
map1 = new Map([...map1.entries()].sort((a, b) => b[0] - a[0]));
for (let [key, value] of map1) {
console.log(key, " " );
}
|
Output
Our map :
Map(3) { 4 => 2, 2 => 3, 3 => 10 }
4
3
2
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.
Example: In this example,, we are using Array.from() and sort() Method
Javascript
let map1 = new Map([
[4, 2],
[2, 3],
]);
map1.set(3, 10);
console.log(map1);
const newMap = Array.from(map1).sort((a, b) => a[1] - b[1]);
const sortedMap = new Map(newMap);
console.log(sortedMap);
|
Output
Map(3) { 4 => 2, 2 => 3, 3 => 10 }
Map(3) { 4 => 2, 2 => 3, 3 => 10 }
Share your thoughts in the comments
Please Login to comment...