JS 中Map对象会按照元素的写入顺序来保存,有时我们想对Map中的对象进行排序应该怎么做呢?参考别人的回答这里做一个小小的总结;
假如有以下map
var map=new Map();
map.set("b","8");
map.set("c","10");
map.set("a","1");
map.set("d","7");
map.set("e","3");
现在想根据value从小到大排序,首先转换为数组对象
var arrayObj=Array.from(map);
得到的arrayObj中索引0为map中的key,索引1为map中的value,下面可以采用数组的排序方法
arrayObj.sort(function(a,b){return a[1]-b[1]})
结果为:
(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
0: (2) ["a", "1"]
1: (2) ["e", "3"]
2: (2) ["d", "7"]
3: (2) ["b", "8"]
4: (2) ["c", "10"]
length: 5
__proto__: Array(0)
如果是想按key排序,只需要更改一下sort方法为
arrayObj.sort(function(a,b){return a[0].localeCompare(b[0])})
结果为:
(5) [Array(2), Array(2), Array(2), Array(2), Array(2)]
0: (2) ["a", "1"]
1: (2) ["b", "8"]
2: (2) ["c", "10"]
3: (2) ["d", "7"]
4: (2) ["e", "3"]
length: 5
__proto__: Array(0)
接下来可以这样转换为Map对象:
var result = new Map(arrayObj.map(i => [i[0], i[1]));
结果为:
Map(5) {"a" => "1", "e" => "3", "d" => "7", "b" => "8", "c" => "10"}
size: (...)
__proto__: Map
[[Entries]]: Array(5)
0: {"a" => "1"}
1: {"e" => "3"}
2: {"d" => "7"}
3: {"b" => "8"}
4: {"c" => "10"}
length: 5
参考:
1.Javascript Sort key value pair object based on value
2.Convert object array to hash map, indexed by an attribute value of the Object