 # Sort the keys in a map using JavaScript The topic of this article will be how you can sort the keys in a map using JavaScript. You can refer to either using the array.sort() or array.reverse() methods.

## How to sort the keys in a map

Using the Array.sort() method

The elements of an array can be sorted using JavaScript’s sort() method. The sort() method returns the altered position of the initial array. The array elements are sorted in ascending order using the sort() method by default.

Because Map doesn’t have built-in functions to sort values ​​by key, we’ll use the array’s methods. We have to convert the map value to the array first. Let’s see the example below.

Syntax:

array.sort( comparison function);

Parameters:

• A function that compares two array elements is an optional argument for the sort() method.
• If you omit the comparison function, the sort() method will sort the elements in sort order based on the elements’ Unicode ordinal values, ​​as mentioned earlier.

Code:

var map = new Map();
map.set("3", "Three");
map.set("2", "Two");
map.set("1", "One");

// Using the Array.sort() method
var mapAsc = new Map([...map.entries()].sort());
console.log(mapAsc);

Output:

Map(3) {'1' => 'One', '2' => 'Two', '3' => 'Three'}

We will first convert the map to an array using brackets [] and then use the array’s built-in sort() method. Once the array is sorted, we have an array with pairs of values, and finally, we use a new map to create a new array from the sorted array. So we can sort the keys in a map using JavaScript, and the ids are sorted in ascending value.

### Using array.reverse() methods

The reverse function in Javascript does what its name suggests: to reverse the order of the elements in the array. Specifically, the first element will become the last element. The second element will become the next element. Same as before, but we will replace the sort() function with reserved(). See the following code:

var map = new Map();
map.set("3", "Three");
map.set("2", "Two");
map.set("1", "One");

// Using the array.reverse() methods
var mapAsc = new Map([...map.entries()].reverse());
console.log(mapAsc);

However, with this method, we can only sort the maps sorted by descending value. It will turn into an ascending map. This approach is quite limited in actual use cases. Please consider before using it.

## Summary

To summarize, the article showed you how to sort the keys in a map using JavaScript but using the array.sort() will be the most comprehensive way. You can replace the sort function to get more different results.

Maybe you are interested: