Skip to main content

How to Sort a Map by Key or Value in JavaScript

The Map object in JavaScript is a powerful collection of key-value pairs that, unlike a plain object, remembers the original insertion order of its keys. A common task is to sort a Map based on either its keys or its values. Since Map objects themselves do not have a built-in sort() method, this is accomplished by converting the Map to an array, sorting the array, and then creating a new Map from the sorted result.

This guide will teach you the standard, modern techniques for sorting a Map by its keys and by its values, for both string and numeric data.

The Core Method: Convert -> Sort -> Reconstruct

The fundamental process for sorting any Map is always the same three steps:

  1. Convert: Convert the Map into an array of [key, value] pairs. The easiest way to do this is with the spread syntax (...).
  2. Sort: Use the Array.prototype.sort() method on the array. You will provide a custom comparison function to define the sorting logic (e.g., sort by key or sort by value).
  3. Reconstruct: Create a new Map() from the sorted array of pairs.

Sorting a Map by its Keys

This is the most common sorting requirement.

For example, you have a Map and you want to order its entries based on the keys.

// Problem: Sort this Map by its keys.
const unsortedMap = new Map([
['zulu', 3],
['alpha', 1],
['charlie', 2]
]);

Sorting by String Keys

When keys are strings, you can use String.prototype.localeCompare() for a reliable alphabetical sort.

const unsortedMap = new Map([
['zulu', 3],
['alpha', 1],
['charlie', 2]
]);

// Convert to an array, sort by the first element of each pair (the key).
const sortedByKey = new Map(
[...unsortedMap].sort((a, b) => a[0].localeCompare(b[0]))
);

console.log(sortedByKey);

Output:

Map(3) {'alpha' => 1, 'charlie' => 2, 'zulu' => 3}
note

To sort in descending order, simply swap a and b: b[0].localeCompare(a[0]).

Sorting by Numeric Keys

When keys are numbers, the comparison function should use simple subtraction.

Solution:

const unsortedMap = new Map([
[10, 'ten'],
[1, 'one'],
[5, 'five']
]);

// Sort by the first element (the key) using numeric subtraction.
const sortedByKey = new Map(
[...unsortedMap].sort((a, b) => a[0] - b[0])
);

console.log(sortedByKey);

Output:

Map(3) { 1 => 'one', 5 => 'five', 10 => 'ten' }
note

To sort in descending order, swap a and b: b[0] - a[0].

Sorting a Map by its Values

The logic is identical to sorting by keys, but the comparison function will now target the second element of each [key, value] pair.

Sorting by String Values

Use localeCompare() on the value part of the pair.

Solution:

const unsortedMap = new Map([
['c', 'zulu'],
['a', 'alpha'],
['b', 'charlie']
]);

// Sort by the second element of each pair (the value).
const sortedByValue = new Map(
[...unsortedMap].sort((a, b) => a[1].localeCompare(b[1]))
);

console.log(sortedByValue);

Output:

Map(3) { 'a' => 'alpha', 'b' => 'charlie', 'c' => 'zulu' }

Sorting by Numeric Values

Use subtraction on the value part of the pair.

Solution:

const unsortedMap = new Map([
['ten', 10],
['one', 1],
['five', 5]
]);

// Sort by the second element (the value).
const sortedByValue = new Map(
[...unsortedMap].sort((a, b) => a[1] - b[1])
);

console.log(sortedByValue);

Output:

Map(3) { 'one' => 1, 'five' => 5, 'ten' => 10 }

How the Sorting Process Works

Let's break down the one-liner new Map([...map].sort(...)) for clarity.

Step 1: Convert to an Array of Entries The spread syntax (...map) converts the Map object into an array of its [key, value] pairs.

const myMap = new Map([['b', 2], ['a', 1]]);
const entries = [...myMap];
// entries is now [ ['b', 2], ['a', 1] ]

Step 2: Sort the Array The Array.prototype.sort() method sorts this array. We provide a custom comparison function that tells it how to sort.

  • (a, b) => a[0] - b[0]: This function takes two elements from the array (a and b, which are both [key, value] pairs) and subtracts their keys (a[0] and b[0]). The sign of the result determines the order.
  • (a, b) => a[1].localeCompare(b[1]): This compares the values (a[1] and b[1]) as strings.

Step 3: Reconstruct the Map The new Map() constructor can accept an array of [key, value] pairs. Since our array is now sorted, the new Map will be created with its elements in that sorted order.

Conclusion

Because Map objects preserve insertion order, sorting them is a predictable process of converting to an array, sorting it, and creating a new Map.

  • To sort, always follow the Convert -> Sort -> Reconstruct pattern.
  • Use a custom comparison function with sort() to specify whether you are sorting by key (a[0], b[0]) or by value (a[1], b[1]).
  • For numeric sorting, use subtraction (e.g., a[0] - b[0]).
  • For string sorting, use localeCompare() (e.g., a[0].localeCompare(b[0])) for reliable alphabetical ordering.