0

I have to transform an array and I don't know how to, anyone can help me with this?

I have this array:

[
  {clientid: 1, content: 'abc'},
  {clientid: 2, content: 'abc'},
  {clientid: 3, content: 'abc'},
  {clientid: 3, content: 'abc'},
  {clientid: 2, content: 'abc'},
  {clientid: 1, content: 'bcd'},
  {clientid: 2, content: 'abc'},
  {clientid: 1, content: 'def'},
  {clientid: 3, content: 'abc'}
]

and I need an array like this:

[
  { clientid: 1, content: ['abc', 'bcd', 'def'] },
  { clientid: 2, content: ['abc', 'abc', 'abc'] },
  { clientid: 3, content: ['abc', 'abc', 'abc'] },

]

anyone can help me?

Derek Wang
  • 10,098
  • 4
  • 18
  • 39
Rafael de Carvalho
  • 501
  • 1
  • 5
  • 10
  • 1
    Welcome to Stackoverflow. Please take the [tour](https://stackoverflow.com/tour) (and get a badge). Your question lacks any attempt at solving this problem on your own. The idea is for you to try to get something to work and then come here with specific problems you are unable to resolve. Taking the tour and reading about [How to ask a good question](https://stackoverflow.com/help/how-to-ask) in the help center will provide all the information you need. – Randy Casburn Oct 29 '20 at 17:30
  • Does this answer your question? [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – Anurag Srivastava Oct 29 '20 at 17:32
  • 2
    I somewhat disagree. it has clearly stated input and required output. why clutter the question with his failed attempts its just noise. and Derek answered with that outstanding answer. I think this is a good addition to the stack overflow question repository – Bryan Dellinger Oct 29 '20 at 17:39
  • I agree with @BryanDellinger ... It sounds like the OP hit a wall. The question's sufficient to assist anyway. If I have gripes, I'd say it's with the title. Maybe "How to transform an array of objects to group one attribute by another" or something? – chad_ Oct 29 '20 at 17:41
  • @BryanDellinger Somewhat agree with you, the problem may be quite difficult for op to post a solution which may not even near to completion. – Abhishek Gurjar Oct 29 '20 at 17:41

1 Answers1

4

This can be done using Array.prototype.reduce.

const input = [
  {clientid: 1, content: 'abc'},
  {clientid: 2, content: 'abc'},
  {clientid: 3, content: 'abc'},
  {clientid: 3, content: 'abc'},
  {clientid: 2, content: 'abc'},
  {clientid: 1, content: 'bcd'},
  {clientid: 2, content: 'abc'},
  {clientid: 1, content: 'def'},
  {clientid: 3, content: 'abc'}
];

const groupBy = input.reduce((acc, cur) => {
  acc[cur.clientid] ? acc[cur.clientid].content.push(cur.content) : acc[cur.clientid] = {
    clientid: cur.clientid,
    content: [ cur.content ]
  };
  return acc;
}, {});
const output = Object.values(groupBy);
console.log(output);
Derek Wang
  • 10,098
  • 4
  • 18
  • 39