Jebathon
Jebathon

Reputation: 4561

Merge Two Arrays of Objects and combine on same keys

Given A and B of different lengths:

A = [
  {X: "a", Y: 5},
  {X: "b", Y: 10},
  {X: "c", Y: 15}
];

B = [
  {X: "a", Z: 5},
  {X: "d", Z: 10}
];

Produces the following array:

C = [    
  {X: "a", Y: 5, Z: 5},
  {X: "b", Y: 10},
  {X: "c", Y: 15},
  {X: "d", Z: 10}
]

So where X is the same the keys that are not X are joined together. Since "a" shares Y and Z it is added together.

Only when X is the same are they joined.

On top of my head a messy solution would be:

C = A.concat(B);

// filter down C to remove duplicate X's
for (i = 0; i < C.length - 1; i++) {
  for (j = 1; j < C.length; j++) {
    if (C[i]['X'] == C[j]['X']) {
      // concatenate the keys together and delete one pair 
    }
  }
}
// keep on looping until no duplicates...

What would be a proper solution for this?

Upvotes: 0

Views: 92

Answers (1)

The Alpha
The Alpha

Reputation: 146191

I'm confused about the requirement/question but I believe you want something like the following:

var A = [
    {X: "a", Y: 5},
    {X: "b", Y: 10},
    {X: "c", Y: 15}
];

var B = [
    {X: "a", Z: 5},
    {X: "d", Z: 10}
];

var C = A.concat(B), temp = {}, result = [];

C.forEach(function(o, i) {
   temp[o.X] = temp[o.X] || o;
   for(var k in o) temp[o.X][k] = o[k];
});


for(var i in temp) result.push(temp[i]);

console.log(result);

If this is your desired result then it could be re-written in es-6 as well but I kept it simple depending on your code example.

Upvotes: 1

Related Questions