gpt4 book ai didi

javascript - 给定一个 map 如何按值排序以及如果值匹配按键 Javascript 排序?

转载 作者:行者123 更新时间:2023-12-05 01:31:04 53 4
gpt4 key购买 nike

给定 map

{
'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);

最佳答案

值出现在索引 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 Destructuring assignment .

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);

仅供引用: 了解如何使用 Logical operators refer to MDN docs 的基本概念.

关于javascript - 给定一个 map 如何按值排序以及如果值匹配按键 Javascript 排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55530878/

53 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com