With JavaScript, we can easily sort a map by keys or get a sorted map by values using the JavaScript sort() function.
sorted_map_by_keys = new Map([...map_to_sort].sort((a, b) => String(a[0]).localeCompare(b[0])))
sorted_map_by_num_values = new Map([...map_to_sort].sort((a, b) => a[1] - b[1]))
sorted_map_by_str_values = new Map([...map_to_sort].sort((a, b) => String(a[1]).localeCompare(b[1])))
In JavaScript, the map object is useful for holding key-value pairs. By default, the map object orders the key-value pairs by the order of insertion.
Since the default order for a JavaScript map object is by order of insertion, we need to write our own code if we want to sort the map by the keys or the values to get a sorted map.
We can easily get a sorted map in our JavaScript code with the JavaScript sort() function.
Let’s say we have the following Map.
var map = new Map();
map.set('Apple','Good');
map.set('Pear','No');
map.set('Banana','Maybe');
map.set('Lemon','Yes');
We can get a sorted map by keys in our JavaScript code with the sort function applied to the keys in the following way.
sorted_map_by_keys = new Map([...map].sort((a, b) => String(a[0]).localeCompare(b[0])))
console.log(sorted_map_by_keys);
// Output
Map(4) {'Apple' => 'Good', 'Banana' => 'Maybe', 'Lemon' => 'Yes', 'Pear' => 'No'}
You can see now that the map is sorted in alphabetical order by keys.
How to Sort a Map by Values in JavaScript
As we saw above, it is easy to sort a map by the keys of the map. We can also sort a map by values easily in our Javascript code.
If your map has string values or a mix of string and numeric values, we can get a sorted map by string values in the following way using the JavaScript localecompare() function.
Let’s say we have the same map as above. Let’s sort the map by values.
sorted_map_by_str_values = new Map([...map].sort((a, b) => String(a[1]).localeCompare(b[1])))
console.log(sorted_map_by_str_values);
// Output
Map(4) {'Apple' => 'Good', 'Banana' => 'Maybe', 'Pear' => 'No', 'Lemon' => 'Yes'}
If your map only has numeric values, we should use a different sorting function.
Let’s say we have a different map with numeric values.
var map = new Map();
map.set('Apple',4);
map.set('Pear',2);
map.set('Banana',1);
map.set('Lemon',3);
To sort this map by its values, we will use a different sorting function for numeric values.
sorted_map_by_num_values = new Map([...map].sort((a, b) => a[1] - b[1]))
console.log(sorted_map_by_num_values);
// Output
Map(4) {'Banana' => 1, 'Pear' => 2, 'Lemon' => 3, 'Apple' => 4}
As you can see, the map is now sorted by values.
Hopefully this article has been useful for you to understand how to obtain a sorted map in your JavaScript code.
Leave a Reply