Is it possible to sort a ES6 map object?

后端 未结 11 1730
滥情空心
滥情空心 2020-11-28 21:34

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:

11条回答
  •  甜味超标
    2020-11-28 22:07

    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.

提交回复
热议问题