How to sort a Map in JavaScript

avatar
Borislav Hadzhiev

Last updated: Mar 6, 2024
6 min

banner

# Table of Contents

  1. Sort the Keys in a Map using JavaScript
  2. Sort a Map by Value in JavaScript

# Sort the Keys in a Map using JavaScript

Use the sort() method to sort the keys in a Map.

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()); // ๐Ÿ‘‡๏ธ {'z' => 'three', 'b' => 'two', 'a' => 'one'} console.log(sortedDesc);

sort the keys in map

The code for this article is available on GitHub

If the keys in your Map are numbers, use the following code sample instead.

index.js
// โœ… 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);

if keys in your map are numbers

The code for this article is available on GitHub

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]);

# Sort the Keys in a Map with String keys

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());

sort keys in map with string keys

The code for this article is available on GitHub
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.

# Sort the Keys in a Map with String keys in descending order

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'}

sort keys in map with string keys in descending order

The code for this article is available on GitHub

# Sort the Keys in a Map with Numeric keys

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 sample 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.

# Sort a Map by value in JavaScript

To sort a Map by value:

  1. Get an array of the Map's entries using the spread syntax (...)
  2. Call the sort() method on the array
  3. Pass the result to the Map() constructor
index.js
// โœ… When VALUES are NUMBERS const map2 = new Map([ ['three', 3], ['one', 1], ['two', 2], ]); // โœ… Sort by Value Ascending (low to high) const sortNumAsc = new Map([...map2].sort((a, b) => a[1] - b[1])); // ๐Ÿ‘‡๏ธ {'one' => 1, 'two' => 2, 'three' => 3} console.log(sortNumAsc); // ---------------------------------------------------- // โœ… Sort by Value Descending (high to low) const sortedNumDesc = new Map([...map2].sort((a, b) => b[1] - a[1])); // ๐Ÿ‘‡๏ธ {'three' => 3, 'two' => 2, 'one' => 1} console.log(sortedNumDesc);
The code for this article is available on GitHub

If the values in your Map are strings, use the following code sample instead.

index.js
// โœ… When VALUES are STRINGS const map1 = new Map([ ['three', 'c'], ['one', 'a'], ['two', 'b'], ]); // โœ… Sort by Value Ascending (low to high) const sortedAsc = new Map([...map1].sort((a, b) => (a[1] > b[1] ? 1 : -1))); // ๐Ÿ‘‡๏ธ {'one' => 'a', 'two' => 'b', 'three' => 'c'} console.log(sortedAsc); // ---------------------------------------------------- // โœ… Sort by Value Descending (high to low) const sortedDesc = new Map([...map1].sort((a, b) => (a[1] > b[1] ? -1 : 1))); // ๐Ÿ‘‡๏ธ {'three' => 'c', 'two' => 'b', 'one' => 'a'} console.log(sortedDesc);

The code snippet shows how to sort a Map by value in ascending and descending order, for both string and number values.

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 map2 = new Map([ ['three', 3], ['one', 1], ['two', 2], ]); // ๐Ÿ‘‡๏ธ [['three', 3], ['one', 1], ['two', 2]] console.log([...map2]);

The next step is to call the sort() method on the array, passing it a function.

The function we passed to the sort() method defines the sort order.

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

index.js
// โœ… When VALUES are NUMBERS const map2 = new Map([ ['three', 3], ['one', 1], ['two', 2], ]); // โœ… Sort by Value Ascending (low to high) const sortNumAsc = new Map([...map2].sort((a, b) => a[1] - b[1])); // ๐Ÿ‘‡๏ธ {'one' => 1, 'two' => 2, 'three' => 3} console.log(sortNumAsc);
The code for this article is available on GitHub

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 sample above:

  • If the second element (the value) in the a array minus the second 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.

# Sort a Map by value in descending order

If you need to sort the Map by value in descending order, just subtract the value of a from the value of b.

index.js
// โœ… When VALUES are NUMBERS const map2 = new Map([ ['three', 3], ['one', 1], ['two', 2], ]); // โœ… Sort by Value Descending (high to low) const sortedNumDesc = new Map([...map2].sort((a, b) => b[1] - a[1])); // ๐Ÿ‘‡๏ธ {'three' => 3, 'two' => 2, 'one' => 1} console.log(sortedNumDesc);
The code for this article is available on GitHub

# Sort a Map with string values by Value

We used the same approach to sort a Map by string values.

index.js
// โœ… When VALUES are STRINGS const map1 = new Map([ ['three', 'c'], ['one', 'a'], ['two', 'b'], ]); // โœ… Sort by Value Ascending (low to high) const sortedAsc = new Map([...map1].sort((a, b) => (a[1] > b[1] ? 1 : -1))); // ๐Ÿ‘‡๏ธ {'one' => 'a', 'two' => 'b', 'three' => 'c'} console.log(sortedAsc);

This time we check if the UTF-16 code unit of the value in the a array is greater than the value in the b array and return 1 if it is, otherwise, we return -1.

If we return 1 (greater than 0), then we sort b before a.

# Sort a Map with string values by Value in descending order

You could change the ordering to descending by changing the places of 1 and -1.

index.js
// โœ… When VALUES are STRINGS const map1 = new Map([ ['three', 'c'], ['one', 'a'], ['two', 'b'], ]); // โœ… Sort by Value Descending (high to low) const sortedDesc = new Map([...map1].sort((a, b) => (a[1] > b[1] ? -1 : 1))); // ๐Ÿ‘‡๏ธ {'three' => 'c', 'two' => 'b', 'one' => 'a'} console.log(sortedDesc);
The code for this article is available on GitHub

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

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.

Copyright ยฉ 2024 Borislav Hadzhiev