[CodeKata] topK 함수

zhflsdl보보·2022년 11월 10일
0

알고리즘

목록 보기
2/2
function topK(nums, k) {
  let obj = {};
  nums.map(num => {
    if(obj[num]) {
      // 1 이 있으면
      obj[num] = obj[num]+1; // {'1': 2}
    } else {
      // 1 이 없으면
      obj[num] = 1; // {'1': 1}
    }
  })
  console.log(obj);
  
  let objSort = Object.keys(obj).sort((a,b)=> {return obj[b]-obj[a]});
  
  console.log(objSort);
  
  let result = objSort.slice(0,k).map((el)=>Number(el[0]));
  
  console.log(result);
}

console.log(topK([3,3,3,3,4,4,4,4,4,2,2,2,1], 2))

여러가지 난관들
1. Array -> Object 바꾸기 ⭕
2. value: 숫자 개수인 Object로 바꾸기 ⭕
3. sort() 이해하기, a-b, 내림차순 & 오름차순 ❌
4. map(el) => Number(el[0]) 이해하기 ❌

망할 너무 어려워 이게뭐람
sort 이렇게 쓰는거 왜 처음본거야 으악 살려줘

profile
매일매일 성장하는 개발자

0개의 댓글