[英]Given a Map how to sort by value and if value matches sort by key Javascript?
給定地圖
{
'i' => 2,
'love' => 2,
'leetcode' => 1,
'coding' => 1
}
我想要,
Map
排序 預期
{
"i" => 2,
"love" => 2,
"coding" => 1,
'leetcode' => 1,
}
解決方案我試過了
let map = new Map(); map.set("i", 2); map.set("love", 2); map.set("coding", 1); map.set("live", 1); let output = new Map([...map.entries()].sort((a, b) => { //if b[0] and a[0] matches sort by key stuck here return b[0] - a[0]; })); console.log(output);
您需要使用String#localeCompare
升序對遞減的計數和字符串進行排序。
第一部分取兩個值的delta,而Array#sort
期望一個值
小於零然后a
小於b
,這意味着兩者都有正確的順序,如1 - 2
,你得到-1
,
等於零,這意味着機器人元素具有相同的值,如7 - 7
,或
大於零,這意味着兩個元素都必須交換,如5 - 3
。
相同的結果返回localeCompare
和字符串。
let map = new Map(); map.set("coding", 1); map.set("love", 2); map.set("live", 1); map.set("i", 2); let output = new Map([...map].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))); console.log([...output]);
值存在於索引1
因此將索引更新為1
以進行基於值的排序,並使用String#localeCompare
進行字符串比較。
let map = new Map(); map.set("i", 2); map.set("love", 2); map.set("coding", 1); map.set("live", 1); // for sorting based on number we need to return the difference // in case those are equals difference would be 0(falsy value) // and the or part will be executed and returns(string comaprison) let output = new Map([...map].sort((a,b) => b[1] - a[1] || a[0].localeCompare(b[0]) )); console.log(...output);
或者使用ES6解構分配 。
let map = new Map(); map.set("i", 2); map.set("love", 2); map.set("coding", 1); map.set("live", 1); let output = new Map([...map].sort( ([k1, v1], [k2, v2]) => v2 - v1 || k1.localeCompare(k2) )); console.log(...output);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.