-2

I have this array:

array = [
    {
      "id": 1,
      "title": "Welcome to /r/artificial!",
      "author": "CyberByte",
      "ups": 128,
      "comments": 16,
      "created_at": "2017-06-19T20:16:35.000Z"
    },
    {
      "id": 2,
      "title": "Welcome",
      "author": "Igor",
      "ups": 12,
      "comments": 06,
      "created_at": "2017-06-19T20:16:35.000Z"
    },
    {
      "id": 3,
      "title": "Teste",
      "author": "CyberByte",
      "ups": 11,
      "comments": 1,
      "created_at": "2017-06-19T20:16:35.000Z"
    },
    ]

I want to group them by author and sum the ups and comments. I'm trying to use reduce. How can I achieve this in plain javascript ?

Mosè Raguzzini
  • 15,399
  • 1
  • 31
  • 43
Igor Martins
  • 2,015
  • 7
  • 36
  • 57

1 Answers1

1

This is now closed as duplicate, but I have an answer, so I figured I may as well post it:

const array = [
{
"id": 1,
"title": "Welcome to /r/artificial!",
"author": "CyberByte",
"ups": 128,
"comments": 16,
"created_at": "2017-06-19T20:16:35.000Z"
},
{
"id": 2,
"title": "Welcome",
"author": "Igor",
"ups": 12,
"comments": 6,
"created_at": "2017-06-19T20:16:35.000Z"
},
{
"id": 3,
"title": "Teste",
"author": "CyberByte",
"ups": 11,
"comments": 1,
"created_at": "2017-06-19T20:16:35.000Z"
},
]

const results = array.reduce((prev, curr) => ({
  ...prev,
  [curr.author]: {
    comments: (prev[curr.author] ? prev[curr.author].comments : 0) + curr.comments,
    ups: (prev[curr.author] ? prev[curr.author].ups : 0) + curr.ups
  }
}), {});

console.dir(results)
OliverRadini
  • 6,238
  • 1
  • 21
  • 46