> 기초/도와줘요!
TIL-2024.04.14 - TIPS - Map() sort 방법 (value 먼저 key 다음)
Janku
2024. 4. 14. 22:12

요구 사항:
1. { 'b' => 2, 'a' => 1, 'c' => 3, 'd' => 2 } 와 같이 뒤죽박죽 되어있는 Map을 정렬해주는데,
- value가 다른 경우 value를 우선 정렬
- value가 같은 경우는 key의 알파벳 순서대로 정렬
목표:
{ 'a' => 1, 'd' => 2, 'b' => 2, 'c' => 3 } 와 같은 형태
관련 코드:
let myMap = new Map();
myMap.set("b", 2);
myMap.set("a", 1);
myMap.set("c", 3);
myMap.set("d", 2); // Adding another entry with the same value
// Convert Map to array of [key, value] pairs
let mapEntries = Array.from(myMap);
// Sort the array by values first, then by keys if values are the same
mapEntries.sort((a, b) => {
// Compare values (a[1] and b[1])
if (a[1] !== b[1]) {
return a[1] - b[1]; // Sort by value (ASC)
// return b[1] - a[1]; // Sort by value (DESC)
} else {
// If values are the same, compare keys (a[0] and b[0])
if (a[0] > b[0]) {
return 1;
} else if (a[0] < b[0]) {
return -1;
} else {
return 0; // Shouldn't reach this point for Map keys (unique keys)
}
}
});
// Create a new Map from the sorted array
let sortedMap = new Map(mapEntries);
console.log(sortedMap);
// Output: Map(4) { 'a' => 1, 'd' => 2, 'b' => 2, 'c' => 3 }