The White Rabbit

I would spend 55 minutes defining the problem and then five minutes solving it. (Albert Einstein)

Published on Monday, 6 March 2023

Tags: code5 typescript2 javascript1

Sort Map Object in Javascript by values

A simple one-liner to convert a Javascript/Typescript Map Object to an array sorted according to the Map's value.


Technically, Map objects can't be sorted because they are not an ordered data structure. Indeed, as soon as you iterate over your Map object using the .entries() method, you would get the items in the insertion order.

Still, you can convert a Map to an array. For example let's define a new sample Map<string, number>:

let myMap: Map<string, number> = new Map();

myMap.set('some', 1);
myMap.set('items', 1);
myMap.set('here', 1);
myMap.set('and', 2);
myMap.set('there', 2);

console.log(myMap);

/*OUTPUT
Map(5) {
  'some' => 1,
  'items' => 1,
  'here' => 1,
  'and' => 2,
  'there' => 2
}
*/

We can convert it to an array of keys Array<string> (unsorted) using the .keys() method. The expected output is an array of keys following the Map insertion order.

let myArray_unsorted = Array.from(myMap.keys());

console.log(myArray_unsorted);
/*OUTPUT
[ 'some', 'items', 'here', 'and', 'there' ]
*/

We can also to create a sorted array of keys by e.g. decreasing Map values (replace b[1]-a[1] with a[1]-b[1] if you need increasing order).

let myArray_sorted = Array.from(myMap.entries()).sort((a,b) => b[1]-a[1]).map((a) => a[0]);

console.log(myArray_sorted);
/*OUTPUT
[ 'and', 'there', 'some', 'items', 'here' ]
*/

Instead, if you want to keep both keys and values while preserving the value-based sorting, you can simply skip the .map() part.

let myArray_sorted = Array.from(myMap.entries()).sort((a,b) => b[1]-a[1]);

console.log(myArray_sorted);
/*OUTPUT
[
  [ 'and', 2 ],
  [ 'there', 2 ],
  [ 'some', 1 ],
  [ 'items', 1 ],
  [ 'here', 1 ]
]
*/