-
TIL-2024.04.14 - TIPS - Map() sort 방법 (value 먼저 key 다음)> 기초/도와줘요! 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 }
'> 기초 > 도와줘요!' 카테고리의 다른 글
TIL-2024.07.04 - TIPS - 다중 commit 하나로 합치기 (0) 2024.07.04 TIL-2024.07.01 - TIPS - React + Docker + Nginx + Git Action (0) 2024.07.01 TIL-2024.02.16 - Tips - .sort() 와 .sort((a,b) => a-b)) 차이 (0) 2024.02.16 001_JS_Object 타입에서 원하는 값 찾고 바꾸기 (0) 2022.06.20