0
const input = [{diagramId: 123, data: [{id: 1, content: content1}]},
                  {diagramId: 123, data: [{id: 2, content: content2}, 
                                          {id: 23, content: conent23}] },
                  {diagramId: 234, data: [{id: 3, content: content3}]}]

Desired output: 
const output = [{diagramId: 123, data: [{id: 1, content: content1},
                                        {id: 2, content: content2},
                                        {id: 23, content: content23}]}, 
                {diagramId: 234, data: [{id: 3, content: content3}]}]
                                         

As you can see above, I want to array method to combine objects that share the same property value (diagramId) to form a new object that condenses their other property together into an array under the other property.

I used for loops, but was rejected for PR due to readability issues. Is it possible to use Array.reduce() to do this?

1 Answer 1

4

Yeah, you can easily achieve this using reduce

const input = [
  { diagramId: 123, data: [{ id: 1, content: "content1" }] },
  {
    diagramId: 123,
    data: [
      { id: 2, content: "content2" },
      { id: 23, content: "conent23" },
    ],
  },
  { diagramId: 234, data: [{ id: 3, content: "content3" }] },
];


const result = input.reduce((acc, curr) => {
  const { diagramId, data } = curr;
  const findObj = acc.find((o) => o.diagramId === diagramId);
  if (!findObj) {
    acc.push({ diagramId, data });
  } else {
    findObj.data.push(...data);
  }
  return acc;
}, []);

console.log(result);

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

1 Comment

Thanks for quick reply! I got lost on the return acc part. Thanks.

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.