Hi good people! I need help with some JavaScript challenge:
QUESTION: Write a function called getSongCountByArtist which takes in an array of songs and returns an object. The keys in the object should be artist names, and the values should be the number of songs by that artist in the original array.
My code Solution:
function getSongCountByArtist(arr){
return arr.reduce(function(acc,val){
let artistSong = val.name;
let songNo = artistSong.length;
return acc[val.artist] + songNo;
}, {})
}
getSongCountByArtist(songs); //NaN
data source https://github.com/PJMantoss/iterators2/blob/master/data.js
PROBLEM EXPLANATION: The function is supposed to return an object with artist
names as keys and number of songs by the artist as values. But On running getSongCountByArtist(songs) it returns NaN
. How can I refactor my code to work? Thank you
Do not use reduce.
Try :
Array.from(new Set(songs.map(e => e.artist).sort()).values()).map(e => {let obj = {}; obj[e] = songs.filter(f => f.artist == e).length; return obj;})