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?

5
  • 1
    Welcome to Stackoverflow. Please take the 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 in the help center will provide all the information you need. Commented Oct 29, 2020 at 17:30
  • Does this answer your question? Most efficient method to groupby on an array of objects Commented Oct 29, 2020 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 Commented Oct 29, 2020 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? Commented Oct 29, 2020 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. Commented Oct 29, 2020 at 17:41

1 Answer 1

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.