-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 ?

3
  • 1
    Could you update the question to include what you've tried so far? Commented Oct 30, 2018 at 16:12
  • Check here : stackoverflow.com/questions/40774697/… Commented Oct 30, 2018 at 16:12
  • 2
    reduce is plain javascript. please add what you have tried. Commented Oct 30, 2018 at 16:12

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.