JavaScript

Sort the Keys in a Map Using JavaScript

A map is a unique object in JavaScript that holds items in key-value pairs. Both primitive data and object data can be stored within the map. The key-value pair is returned in the same sequence as they were inserted when iterating through the map object. For sorting keys in maps in ascending and descending order, use the sort() and reverse() methods.

This post will define the methods to sort the map keys using JavaScript.

How to Sort the Map Keys Using JavaScript?

For sorting the keys in the map, utilize the given JavaScript pre-built methods:

Let’s look at the working of these methods.

Method 1: Sort the Keys in a Map Using sort() Method

To sort the keys in the map in ascending order, use the “sort()” method with the spread operator “” in the map object. It is utilized to get an array of the Map’s entries to sort using the sort() method.

Syntax

The following syntax is used for sorting the map keys in ascending order:

new Map([...map.entries()].sort())

Example

Create a map in a key-value pair:

let map = new Map([

  [10, 'JavaScript'],

  [13, 'CSS'],

  [23, 'HTML'],

]);

Create a new map object and call the sort() method with the spread operator as a parameter that gets the map entries for sorting and storing the returned sorted array in variable “ascMapKeys”:

var ascMapKeys = new Map([...map.entries()].sort());

Print the array of sorted map keys on the console:

console.log(ascMapKeys);

Output

If you want to sort the keys of the map in descending order, follow the given section.

Method 2: Sort the Keys in a Map Using reverse() Method

For sorting map keys in descending order, use the “reverse()” method with a spread operator. The reverse() method reverses the order of the elements in an array.

Syntax

Use the given syntax for sorting the array in reverse order using the reverse() method:

new Map([...map.entries()].reverse())

Example

Call the reverse() method in the new map object as an argument to reverse the order of the keys:

var descMapKeys = new Map([...map.entries()].reverse());

Finally, print the resultant array of reverse order keys:

console.log(descMapKeys);

The output indicates that the keys are successfully sorted in descending order:

We have gathered all the necessary information for sorting the map keys in JavaScript.

Conclusion

To sort the keys in the map in ascending order, use the “sort()” method, and for descending order, utilize the “reverse()” method with a spread operator. More specifically, the spread operator gets an array of the Map’s entries to sort in ascending and descending order. In this post, we defined the methods to sort the keys in the map using JavaScript.

About the author

Farah Batool

I completed my master's degree in computer science. I am an academic researcher and love to learn and write about new technologies. I am passionate about writing and sharing my experience with the world.