Here are two ways to sort a map by value in JavaScript:
- Using Map.entries() and sort()
- Using Array.from() and sort()
Method 1: Using Map.entries() and sort()
The Map.entries() method is used to convert the Map object into an array of key-value pairs and then sort that array based on the values using sort() method.
Here is the step-by-step guide to sort a map by value.
- Convert the map entries to an array.
- Sort the array based on the values.
- Create a new map and insert the sorted entries into it.
let myMap = new Map();
myMap.set('a', 5);
myMap.set('b', 3);
myMap.set('c', 8);
myMap.set('d', 1);
let sortedEntries = [...myMap.entries()].sort((a, b) => a[1] - b[1]);
let sortedMapByEntries = new Map(sortedEntries);
console.log(sortedMapByEntries);
Output
Map(4) { 'd' => 1, 'b' => 3, 'a' => 5, 'c' => 8 }
Method 2: Using Array.from() and sort()
You can use the Array.from() method to convert the Map into an array of key-value pairs. After the conversion, sort the array using sort() and create a new map from the sorted entries.
let myMap = new Map();
myMap.set('a', 5);
myMap.set('b', 3);
myMap.set('c', 8);
myMap.set('d', 1);
let sortedArray = Array.from(myMap).sort((a, b) => a[1] - b[1]);
let sortedMapFromArray = new Map(sortedArray);
console.log(sortedMapFromArray);
Output
Map(4) { 'd' => 1, 'b' => 3, 'a' => 5, 'c' => 8 }
That’s it!
Related posts
How to Sort ES6 Set in JavaScript
TypeError: set.sort is not a function

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.