Sort a Map based on the keys in JavaScript
This post will discuss how to sort a Map based on the keys in JavaScript.
Sorting a map by its keys in JavaScript is a task that involves ordering the key-value pairs of a map object based on the keys, either in ascending or descending order, or by some custom logic. By default, a map preserves the insertion order of its elements, but sometimes we may want to sort the elements by their keys. Here are some of the common methods:
1. Using Array.sort() and spread syntax
This is a simple and concise way to sort a map by its keys by using the spread syntax (…) to convert the map into an array of [key, value] pairs, and then using the sort() function to sort the array by comparing the keys, and then create a new map from the sorted array using the Map() constructor. The sort() function takes an optional compare function as an argument, which can be used to define the sorting logic. It should return a negative number, zero, or a positive number depending on whether the first key is less than, equal to, or greater than the second key. For example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Create a map with some key-value pairs const map = new Map([['one', 1], ['two', 2], ['three', 3], ['four', 2]]); // Use spread syntax to convert the map into an array of entries const array = [...map]; // or use Array.from(map) // Sort the array by the keys const sortedArray = array.sort((a, b) => String(a[0]).localeCompare(b[0])); // Create a new map from the sorted array const sortedMap = new Map(sortedArray); // Map(4) { 'four' => 2, 'one' => 1, 'three' => 3, 'two' => 2 } console.log(sortedMap); |
2. Using a custom class
Another option is to create a custom class that extends the Map object and add functions to add and delete keys from the map. It also adds functions to sort and return the map in different formats. This method works well for maps that require more functionality and flexibility than the built-in Map object. For example, one possible implementation of the custom class could be:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
class MyMap extends Map { constructor(iterable) { // call the Map constructor with the optional iterable argument super(iterable); } add(key, value) { super.set(key, value); // call the Map.set function return this; // return the map object for chaining } delete(key) { super.delete(key); // call the Map.delete function return this; // return the map object for chaining } sorted(ascending = true) { if (ascending) { // sort the keys by ascending order return new Map([...this].sort((a, b) => String(a[0]).localeCompare(b[0]))); } else { // sort the keys by descending order return new Map([...this].sort((a, b) => String(b[0]).localeCompare(a[0]))); } } } // create a custom map const map = new MyMap([['one', 1], ['two', 2], ['three', 3], ['four', 2]]); // MyMap(4) [Map] { 'one' => 1, 'two' => 2, 'three' => 3, 'four' => 2 } console.log(map); // get a sorted map by its keys const sortedMap = map.sorted(); // Map(4) { 'four' => 2, 'one' => 1, 'three' => 3, 'two' => 2 } console.log(sortedMap); |
3. Using Lodash library
We can also use a third-party library such as lodash to help sort a map by its keys in JavaScript. Lodash has a function called sortBy() that takes an object or an array and one or more iteratee functions as arguments and returns a new array of elements sorted by the iteratee functions. We can use this function to sort a map by its keys by passing it to the iteratee function. Here’s an example of its usage:
|
1 2 3 4 5 6 7 8 9 10 |
let _ = require("lodash"); // import lodash library // Create a map with some key-value pairs const map = new Map([['one', 1], ['two', 2], ['three', 3], ['four', 2]]); // Sort the map by its keys using lodash let sortedMap = new Map(_.sortBy(Array.from(map), [0])); // Map(4) { 'four' => 2, 'one' => 1, 'three' => 3, 'two' => 2 } console.log(sortedMap); |
That’s all about sorting a Map based on the keys in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)