Home > Mobile >  Add objects of two different Arrays
Add objects of two different Arrays

Time:09-22

I have two arrays and each of them has objects. How best can I simplify adding two objects into one but in a new list. e.g

a = [{a:1, b:2, c:3}, {d:1, e:4, f:2}]
b = [{m:1, n:2, o:4}, {r:1,s:3,u:5}, {k:1,j:4,f:8}]

z = [{a:1, b:2, c:3, m:1, n:2, o:4}, {d:1, e:4, f:2, r:1,s:3,u:5}, {k:1,j:4,f:8}]

Suppose you have list a and b, I want to add the objects of each position together in list z.

CodePudding user response:

You could merge the two object in this way:

let a = [{a:1, b:2, c:3}, {d:1, e:4, f:2}]
let b = [{m:1, n:2, o:4}, {r:1,s:3,u:5}, {k:1,j:4,f:8}]

let z = [];

b.forEach((x, i) => {
     let merged = {...x, ...a[i]};
     z.push(merged)
})

console.log(z);

CodePudding user response:

I'd go over the maximum length of a and b and use Object.assign to copy the values. Assuming you want a generic solution to any two arrays, where either can be longer than the other, note that you need to check the lengths as you go:

z = [];
for (let i = 0; i < Math.max(a.length, b.length);   i) {
    const result = i < a.length ? a[i] : {};
    Object.assign(result, i < b.length ? b[i] : {});
    z.push(result);
}

CodePudding user response:

Try this :

const a = [{a:1, b:2, c:3}, {d:1, e:4, f:2}];
const b = [{m:1, n:2, o:4}, {r:1,s:3,u:5}, {k:1,j:4,f:8}];
let c = [];

if(a.length > b.length){
    c = a.map((e,i) => {
     return {
        ...e,
        ...b[i]
     }
   });
}else{
  c = b.map((e,i) => {
      return {
        ...e,
        ...a[i]
     }
  });
}
console.log(c);

CodePudding user response:

You could check first the length of both arrays and then merge them.

const a = [{ a: 1, b: 2, c: 3 }, { d: 1, e: 4, f: 2 }]
const b = [{ m: 1, n: 2, o: 4 }, { r: 1, s: 3, u: 5 }, { k: 1, j: 4, f: 8 }]

const mergeArrays = (arr1, arr2) => arr1.map((x, i) => ({ ...x, ...arr2[i] }))

const z = a.length > b.length ? mergeArrays(a, b) : mergeArrays(b, a);
console.log(z);

CodePudding user response:

Logic

  • Create a new array with length of maximum of both array. Using that array indices return data from array a and b

const a = [{ a: 1, b: 2, c: 3 }, { d: 1, e: 4, f: 2 }]
const b = [{ m: 1, n: 2, o: 4 }, { r: 1, s: 3, u: 5 }, { k: 1, j: 4, f: 8 }];
const z = Array.from({ length: Math.max(a.length, b.length) }, (_, index) => ({ ...a[index] , ...b[index] }));
console.log(z);

  • Related