re: Returning an object using reduce() VIEW POST


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 increment acc[val.artist] by songNo and the return acc.

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

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

     arr[artistName] = artistSong;

        artistSong += 1;

    return acc;

}, {})

getSongCountByArtist(songs); // {}

Thank you


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;
    return acc;
  }, {});

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

code of conduct - report abuse