https://programmers.co.kr/learn/courses/30/lessons/42579
index: 고유 번호
{
classic: {
count: 1450,
songs: [{ index: 3, play: 800 }, { index: 0, play: 500 }]
},
pop: {
count: 3100,
songs: [{ index: 4, play: 2500 }, { indx: 1, play:600 }]
}
}
1. 인기 순으로 장르를 정렬 =>
[pop, classic]
2. 각 노래들을 플레이 횟수 / 인덱스 번호로 정렬 =>
eachSongs.map(eachSong.sort((a, b) => b.play - a.play || a.index - b.index))
3. 인덱스 번호 2개 씩 slice
=> [...popSongs.map({ index }) => index).slice(0,2), ...]
function makeAlbumCollection(genres, plays) {
const albumCollection = {};
plays.forEach((play, index) => {
const album = albumCollection[genres[index]];
if (album) {
album.count += play;
album.songs.push({
play,
index,
});
} else {
albumCollection[genres[index]] = {
count: play,
songs: [
{
play,
index,
},
],
};
}
});
return albumCollection;
}
function getPopularGenres(collection) {
return Object.keys(collection).sort(
(a, b) => collection[b].count - collection[a].count
);
}
function sortBestSongs(collection) {
Object.keys(collection).forEach((genre) => {
collection[genre].songs = collection[genre].songs.sort(
(a, b) => b.play - a.play || a.index - b.index
);
});
}
function solution(genres, plays) {
const albumCollection = makeAlbumCollection(genres, plays);
const popularGenres = getPopularGenres(albumCollection);
sortBestSongs(albumCollection);
return popularGenres.reduce(
(acc, genre) =>
acc.concat(
albumCollection[genre].songs.map(({ index }) => index).slice(0, 2)
),
[]
);
}