Is it possible to sort a ES6 map object?

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

    As far as I see it's currently not possible to sort a Map properly.

    The other solutions where the Map is converted into an array and sorted this way have the following bug:

    var a = new Map([[1, 2], [3,4]])
    console.log(a);    // a = Map(2) {1 => 2, 3 => 4}
    
    var b = a;
    console.log(b);    // b = Map(2) {1 => 2, 3 => 4}
    
    a = new Map();     // this is when the sorting happens
    console.log(a, b); // a = Map(0) {}     b = Map(2) {1 => 2, 3 => 4}
    

    The sorting creates a new object and all other pointers to the unsorted object get broken.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-28 22:15

    The snippet below sorts given map by its keys and maps the keys to key-value objects again. I used localeCompare function since my map was string->string object map.

    var hash = {'x': 'xx', 't': 'tt', 'y': 'yy'};
    Object.keys(hash).sort((a, b) => a.localeCompare(b)).map(function (i) {
                var o = {};
                o[i] = hash[i];
                return o;
            });
    

    result: [{t:'tt'}, {x:'xx'}, {y: 'yy'}];

    0 讨论(0)
  • 2020-11-28 22:23

    You can convert to an array and call array soring methods on it:

    [...map].sort(/* etc */);
    
    0 讨论(0)
  • 2020-11-28 22:28

    One way is to get the entries array, sort it, and then create a new Map with the sorted array:

    let ar = [...myMap.entries()];
    sortedArray = ar.sort();
    sortedMap = new Map(sortedArray);
    

    But if you don't want to create a new object, but to work on the same one, you can do something like this:

    // Get an array of the keys and sort them
    let keys = [...myMap.keys()];
    sortedKeys = keys.sort();
    
    sortedKeys.forEach((key)=>{
      // Delete the element and set it again at the end
      const value = this.get(key);
      this.delete(key);
      this.set(key,value);
    })
    
    0 讨论(0)
提交回复
热议问题