Is it possible to sort a ES6 map object?

后端 未结 11 1681
滥情空心
滥情空心 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:14

    The idea is to extract the keys of your map into an array. Sort this array. Then iterate over this sorted array, get its value pair from the unsorted map and put them into a new map. The new map will be in sorted order. The code below is it's implementation:

    var unsortedMap = new Map();
    unsortedMap.set('2-1', 'foo');
    unsortedMap.set('0-1', 'bar');
    
    // Initialize your keys array
    var keys = [];
    // Initialize your sorted maps object
    var sortedMap = new Map();
    
    // Put keys in Array
    unsortedMap.forEach(function callback(value, key, map) {
        keys.push(key);
    });
    
    // Sort keys array and go through them to put in and put them in sorted map
    keys.sort().map(function(key) {
        sortedMap.set(key, unsortedMap.get(key));
    });
    
    // View your sorted map
    console.log(sortedMap);
    

提交回复
热议问题