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
Top comments (5)
You're code is very close, but the function given to reduce should return an object. Instead of returning
acc[val.artist] + songNo
, you could incrementacc[val.artist]
bysongNo
and the returnacc
.Although I'm not sure why you're adding the length of the song name. Maybe just increment by 1 each time?
Hi Craig! I have applied your suggestion. It's still not returning the right data. It returns an empty object. Please See below:
function getSongCountByArtist(arr){
}
//test
getSongCountByArtist(songs); // {}
Thank you
Seems I didn't describe my idea very well. Here's the code I had in mind:
Hello Craig! I've implemented your code and it works perfectly now. Thanks a million! I appreciate your help.
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;})