Given Map
{
'i' => 2,
'love' => 2,
'leetcode' => 1,
'coding' => 1
}
I want to,
- Sort the
Mapbased on value - if the value matches, sort by key where the word with the lower alphabetical order comes first.
Expected
{
"i" => 2,
"love" => 2,
"coding" => 1,
'leetcode' => 1,
}
Solution i have tried
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);
compareFunctionshould beb[0].localeCompare(a[0])...map.entries()is the same as just spreading the map...map.