Is it possible to sort a ES6 map object?

According MDN documentation:

A Map object iterates its elements in insertion order.

You could do it this way:

var map = new Map();
map.set('2-1', "foo");
map.set('0-1', "bar");
map.set('3-1', "baz");

var mapAsc = new Map([...map.entries()].sort());

console.log(mapAsc)

Using .sort(), remember that the array is sorted according to each character’s Unicode code point value, according to the string conversion of each element. So 2-1, 0-1, 3-1 will be sorted correctly.

Leave a Comment