Sort the Keys in a Map using JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Sort the Keys in a Map using JavaScript #

Use the sort() method to sort the keys in a Map, e.g. const sorted = new Map([...map1].sort()). The spread syntax (...) is used to get an array of the Map's entries, which we can sort using the sort method.

index.js
// ✅ When Keys are STRINGS const map1 = new Map([ ['z', 'three'], ['a', 'one'], ['b', 'two'], ]); // 👇️ {'z' => 'three', 'a' => 'one', 'b' => 'two'} console.log(map1); // ✅ Sort Ascending (low to high) const sortedAsc = new Map([...map1].sort()); // 👇️ {'a' => 'one', 'b' => 'two', 'z' => 'three'} console.log(sortedAsc); // ✅ Sort Descending (high to low) const sortedDesc = new Map([...map1].sort().reverse()); console.log(sortedDesc); // 👉️ {'z' => 'three', 'b' => 'two', 'a' => 'one'} // --------------------------------------------------------- // ✅ When keys are NUMBERS const map2 = new Map([ [3, 'three'], [1, 'one'], [2, 'two'], ]); // ✅ Sort Ascending (low to high) const sortNumAsc = new Map([...map2].sort((a, b) => a[0] - b[0])); // 👇️ {1 => 'one', 2 => 'two', 3 => 'three'} console.log(sortNumAsc); // ✅ Sort Descending (high to low) const sortedNumDesc = new Map([...map2].sort((a, b) => b[0] - a[0])); // 👇️ {3 => 'three', 2 => 'two', 1 => 'one'} console.log(sortedNumDesc);

The Map object remembers the insertion order of the keys.

This is why we used the Map() constructor to create a new Map with the correct order.

The spread syntax (...) allows us to get an array containing the Map's entries.

index.js
const map1 = new Map([ ['z', 'three'], ['a', 'one'], ['b', 'two'], ]); // 👇️ [['z', 'three'], ['a', 'one'], ['b', 'two']] console.log([...map1]);

When sorting a Map with string keys, we just have to call the sort() method.

index.js
const map1 = new Map([ ['z', 'three'], ['a', 'one'], ['b', 'two'], ]); // 👇️ [['a', 'one'], ['b', 'two'], ['z', 'three']] console.log([...map1].sort());
This gets us an array containing arrays of key-value pairs, which we can directly pass to the Map constructor to create a new Map with sorted keys.

Here is the complete code snippet:

index.js
// ✅ When Keys are STRINGS const map1 = new Map([ ['z', 'three'], ['a', 'one'], ['b', 'two'], ]); // 👇️ {'z' => 'three', 'a' => 'one', 'b' => 'two'} console.log(map1); // ✅ Sort Ascending (low to high) const sortedAsc = new Map([...map1].sort());
When calling the sort() method on arrays of key-value pairs, we are simply sorting the string conversion of the key-value pairs, e.g.z,three vs a,one.

We used the same approach to sort the Map's keys in descending order. All we had to do is add a call to the reverse() method after sorting.

index.js
// ✅ When Keys are STRINGS const map1 = new Map([ ['z', 'three'], ['a', 'one'], ['b', 'two'], ]); // ✅ Sort Descending (high to low) const sortedDesc = new Map([...map1].sort().reverse()); console.log(sortedDesc); // 👉️ {'z' => 'three', 'b' => 'two', 'a' => 'one'}

If the Map's keys are numbers, you have to pass a function to the sort() method.

The parameter the method takes is a function that defines the sort order.

The function gets called with 2 parameters. In our example with 2 arrays containing key-value pairs.

index.js
const map2 = new Map([ [3, 'three'], [1, 'one'], [2, 'two'], ]); // ✅ Sort Ascending (low to high) const sortNumAsc = new Map([...map2].sort((a, b) => a[0] - b[0])); // 👇️ {1 => 'one', 2 => 'two', 3 => 'three'} console.log(sortNumAsc);

The sort() method uses the following logic to sort the elements in the array:

  • If the return value of the compare function is greater than 0, then sort b before a.

  • If the return value of the compare function is less than 0, then sort a before b.

  • If the return value of the compare function is equal to 0, keep the original order of a and b.

In the code snippet above:

  • If the first element (the key) in the a array minus the first element in the b array returns a value greater than 0, we sort b before a
  • If the subtraction returns a negative number, we sort a before b.
  • If the subtraction returns 0, we keep the original order of a and b.
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.