Search code examples
javascriptecmascript-6

Is it possible to sort a ES6 map object?


Is it possible to sort the entries of a es6 map object?

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

results in:

map.entries = {
    0: {"2-1", foo },
    1: {"0-1", bar }
}

Is it possible to sort the entries based on their keys?

map.entries = {
    0: {"0-1", bar },
    1: {"2-1", foo }
}

Solution

  • 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.