Search code examples
javascriptnode.jsjsonlodash

Sum of an array in which the array is a property of a property in the outer object


{
    'Edsger W. Dijkstra': [ // o
      { author: 'Edsger W. Dijkstra', likes: 5 },
      { author: 'Edsger W. Dijkstra', likes: 10 }
    ],
    'Benizio Mauritez': [
      { author: 'Benizio Mauritez', likes: 12 },
      { author: 'Benizio Mauritez', likes: 8 }
    ]
  }

I have this object which in this case, represents users from a blog in which, I am trying to merge a single author with their total likes already merged, e.g:

{
    [
        author: Edsger W. Dijkstra,
        likes: 15
    ],
    [
        author: Benizio Mauritez, 
        likes: 20
    ],
}

How can I do this? I've already trying reducing their props (Got stucked at re-assigning or creating a new prop out of that), tried lodash's sumBy function so if someone can enlight me on how to do this, I would be very much appreciating it!, many thanks !


Solution

  • You could loop through the authors in your 'input' object, and produce an 'output' object where you sum the 'likes' of the related array...

    Something like this:

    input = {
        'Edsger W. Dijkstra': [ // o
          { author: 'Edsger W. Dijkstra', likes: 5 },
          { author: 'Edsger W. Dijkstra', likes: 10 }
        ],
        'Benizio Mauritez': [
          { author: 'Benizio Mauritez', likes: 12 },
          { author: 'Benizio Mauritez', likes: 8 }
        ]
      };
    
    output = Object.keys(input).map(key => {
     return { author: key, likes: input[key].reduce((a, b) => a + b['likes'], 0) };
    })
    
    console.log(output);
    

    To give a bit more explanation:

    Object.keys(input) will give you an array of the authors in the 'input' object.

    console.log(Object.keys(input));
    //["Edsger W. Dijkstra", "Benizio Mauritez"]
    

    You can then use the map function to create a new array populated with the results of calling a provided function on every element in the calling array.

    output = Object.keys(input).map(key => {
     console.log(input[key]);
    })
    
    /*
    [{
      author: "Edsger W. Dijkstra",
      likes: 5
    }, {
      author: "Edsger W. Dijkstra",
      likes: 10
    }]
    [{
      author: "Benizio Mauritez",
      likes: 12
    }, {
      author: "Benizio Mauritez",
      likes: 8
    }]
    */
    

    Then finally using the reduce method on the inner array (the array referenced of each key) to sum the 'likes'.