DEV Community

loading...

Discussion on: Returning an object using reduce()

Collapse
pjmantoss profile image
PJ Mantoss Author

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){

return arr.reduce(function(acc,val){
    let artistName = val.artist,
        artistSong = val.name;

     arr[artistName] = artistSong;

    if(artistName){
        artistSong += 1;
    }

    return acc;

}, {})

}
//test
getSongCountByArtist(songs); // {}

Thank you

Collapse
craigmc08 profile image
Craig McIlwrath

Seems I didn't describe my idea very well. Here's the code I had in mind:

function getSongCountByArtist(songs) {
  return songs.reduce(function (acc, song) {
    if (acc[song.artist] === undefined) acc[song.artist] = 0;
    acc[song.artist]++;
    return acc;
  }, {});
} 
Thread Thread
pjmantoss profile image
PJ Mantoss Author

Hello Craig! I've implemented your code and it works perfectly now. Thanks a million! I appreciate your help.