Sort Map by Value JavaScript
Sorting a map in JavaScript is a bit more difficult compared to an array. If you use a map instead of an array you can store key-value pairs. Remember that graphs in JavaScript are sorted by insertion, not by their keys or values. Therefore, a sorted map may not retain the original order of keys when sorted by values. So, in this article, we’ll see how to sort maps by value in javascript.
Before we dive into the sorting methods, let’s quickly review maps in JavaScript. A map is a JavaScript object that allows you to associate values (keys) with other values (values). Unlike arrays, maps don’t have a built-in sorting technique, so we have to figure out the solution for sorting ourselves. When it comes to sorting a map by value, we need to employ some additional techniques.
Creating a simple map:
To create a map, first, we need to create a map object like:
const originalMap = new Map([
//Keys-values pairs
]);
Then we need to insert our key-value pairs in square brackets using a comma separator. We must put each key-value pair in separate square brackets as in the below code.
const originalMap = new Map([
['apple', 3],
['banana', 1],
['orange', 2]
]);
console.log(originalMap.keys()); // {'apple', 'banana', 'orange'}
console.log(originalMap.values()) // {3, 1, 2}
And you can log the all keys by using the ‘keys()
‘ method and all values by using ‘values()
‘ method.
2 methods to Sort map by values
Method 1: Using entries() method
In this method, we will convert the map into an array of key-value pairs, sort the array based on the values, and then create a new map from the sorted array.
Example:
// Creating map
const originalMap = new Map([
['B', 2],
['A', 1],
['D', 4],
['C', 3]
]);
//converting map to array and sorting by value
const sortArr = [...originalMap.entries()].sort((a, b) => a[1] - b[1]);
//converting array to map
const sortMap = new Map(sortArr);
//log the sorted map
console.log(sortMap)
Output:
Steps
- In this code, we have created a map with 4 key-value pairs and stored it in the variable ‘
originalMap
‘. - “
...originalMap.entries()
” – We use (…) spread operator for ‘originalMap’, it convert the iterator object into an array. Then we use ‘entries
()’ method, it creates array of [key, value] pairs for each element in the Map. So, this creates a new array with elements representing the key-value pairs from originalMap. sort((a, b) => a[1] - b[1])
– We pass an arrow function as an argument of thesort()
method, the arrow function takes two elements a and b based on the values at index 1 (the values of the key-value pairs).- It subtracts b[1] from a[1], which will result in a negative number if a[1] is smaller, a positive number if a[1] is larger, or zero if they are equal. This way, the sort() method arranges the elements in ascending order of their values and we assigned it to the ‘sortMap’.
- Finally, we convert the array to a map by creating a new map ‘sortMap’. And log that ‘sortMap’
Method 2: Using a Custom Sorting Function
// Creating map
const originalMap = new Map([
['apple', 3],
['banana', 1],
['orange', 2]
]);
// Creating custom function for sorting
const sortedMap = new Map([...originalMap].sort((a, b) => {
// Custom sorting logic based on values
if (a[1] < b[1]) return -1;
if (a[1] > b[1]) return 1;
return 0;
}));
//log the sorted map
console.log(sortedMap)
Output:
Steps:
- Create the map with key-value pairs and assign it in any variable, here we call it ‘originalMap’.
- Then create another map ‘sortedMap’, and use the spread operator
(...)
with ‘originalMap’ to convert an array. - Invoke
Sort()
the method is an array created in the previous step. It takes a comparison function as an argument, which determines the order in which the elements will be sorted. So, It takes two elements a and b based on the values of the key-value pairs. - Inside the function, we check two conditions:
if (a[1] < b[1]) return -1;
: If the value of a is less than the value of b, the function returns -1. This places a before b in the sorted order.
if (a[1] > b[1]) return 1;
: If the value of a is greater than the value of b, the function returns 1. This places an after b in the sorted order.
If the values of a and b are equal, the function returns0
. - Finally, log the
sortedMap
.
Conclusion
So you can sort your map by value in javascript using the above two methods. Comment below if you don’t understand any steps