How to Sort a Map by Value in JavaScript

Here are two ways to sort a map by value in JavaScript:

  1. Using Map.entries() and sort()
  2. Using Array.from() and sort()

How to Sort a Map by Value in JS

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.

  1. Convert the map entries to an array.
  2. Sort the array based on the values.
  3. 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