0

I am trying to get the same group names to merge together. I have looked around to get an idea of how to do this so I have done some research and I wrote the below code.

This is my implementation that isn't working:

const input = [ 
  { people: [{ names: "John" }, { names: "Sam" }], group: "one", },
  { people: [{ names: "George" }], group: "one", },
  { people: [{ names: "Bella" }], group: "two",},
];


var output = [];
input.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.group == item.group;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].people = output[existingIndex].people.concat(item.people);
  }
});
console.log(output)

Desired Output:

const output = [
  {
    people: [{ names: "John" }, { names: "Sam" }, { names: "George" }],
    group: "one",
  },
  {
    people: [{ names: "Bella" }],
    group: "two",
  },
];

1 Answer 1

1
  • Using Array.reduce, you can group by the current array using group key.
  • And from that grouped object, you can get the result you want.

const input = [
  {
    people: [{ names: "John" }, { names: "Sam" }],
    group: "one",
  },
  {
    people: [{ names: "George" }],
    group: "one",
  },
  {
    people: [{ names: "Bella" }],
    group: "two",
  },
];

const groupByKey = input.reduce((acc, cur) => {
  acc[cur.group] ? acc[cur.group].people.push(...cur.people) : acc[cur.group] = cur;
  return acc;
}, {});
const output = Object.values(groupByKey);
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.