문제
매개변수 (장르, 플레이수)
베스트 앨범은 속한 노래가 많이 재생된 장르를 2개 모은다.
장르 내에서 가장 많이 재생된 노래를 2개 뽑는다.
장르 내 재생횟수가 같으면 고유번호가 낮은 노래를 수록한다.
베스트 앨범에 들어갈 노래의 고유번호 리턴
강사 답
function solution(genres, plays) {
const genreMap = new Map();
genres
.map((genre, index) => [genre, plays[index]])
// [ 'classic', 500 ]
// [ 'pop', 600 ]
// [ 'classic', 150 ]
// [ 'classic', 800 ]
// [ 'pop', 2500 ]
.forEach(([genre, play], index) => {
const data = genreMap.get(genre) || { total: 0, songs: [] }; // undefined 방지
genreMap.set(genre, {
// genre가 classic일 경우
total: data.total + play,
songs: [...data.songs, { play, index }] // 비구조 할당
// [{ play:500, index:0 }, { play:150, index:2 }, { play:800, index:3 }]
.sort((a, b) => b.play - a.play)
// [{ play: 800, index: 3 },{ play: 500, index: 0 },{ play: 150, index: 2 }]
.slice(0, 2),
// [{ play: 800, index: 3 },{ play: 500, index: 0 }]
});
});
return [...genreMap]
// ['classic', {total: 1450, songs: [3, 0]}], ['pop', {total: 3100, songs: [4, 1]}]
.sort((a, b) => b[1].total - a[1].total)
// ['pop', {total: 3100, songs: [4, 1]}], ['classic', {total: 1450, songs: [3, 0]}]
.flatMap((item) => item[1].songs)
// [{ play: 2500, index: 4 },
// { play: 600, index: 1 },
// { play: 800, index: 3 },
// { play: 500, index: 0 }]
.map((song) => song.index);
// [4, 1, 3, 0]
}