Dilhan Bhagat
Dilhan Bhagat

Reputation: 49

Javascript : Merge objects in array with the same key not working

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",
  },
];

Upvotes: 0

Views: 63

Answers (1)

Derek Wang
Derek Wang

Reputation: 10204

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

Upvotes: 1

Related Questions