7. Hash Table Problem

프로그래머스, 베스트앨범
// 같은 장르끼리 묶는다.
// 같은 장르에서 플레이순으로 소팅한다.
// 장르를 2개씩 잘라 하나의 배열로 나열한다.

function solution(genres, plays) {
  var answer = [];
  const album = new Map();

  genres
    .map((genre, index) => [genre, plays[index]])
    .forEach(([genre, play], index) => {
      const prevGenre = album.get(genre);

      album.set(genre, {
        total: (prevGenre?.total ?? 0) + play,
        songs: [...(prevGenre?.songs ?? []), [play, index]]
          .sort((a, b) => b[0] - a[0])
          .slice(0, 2),
      });
    });

  return [...album.entries()]
    .sort((a, b) => b[1].total - a[1].total)
    .flatMap((song) => song[1].songs)
    .map((song) => song[1]);

  return answer;
}

Last updated