0

This are the two array that needs merging based on common id, the nested array should also be merged

First Array

const arr1 = [
    { id: 1, name: "sai", accounts: ["a"] },
    { id: 2, name: "King", accounts:[] },
    { id: 3, name: "Queen", accounts:["c"] },
    { id: 4, name: "kai", accounts:["e"] },
  ];

Second Array

const arr2 = [
    { id: 1, age: 23, accounts: ["b"] },
    { id: 2, age: 24, accounts:[] },
    { id: 3, age: 25, accounts:["d"] }
  ];

Output should be

[  
  { id: 1, age: 23, name:"sai", accounts: ["a","b"] },
  { id: 2, age: 24, name: "King", accounts:[] },
  { id: 3, age: 25, name:"Queen", accounts:["c","d"] },
  { id: 4, name: "kai", accounts:["e"] },
] 
1
  • 2
    Please edit the question to show your own efforts at solving this, because Stack Overflow is not a write-my-code-for-me service. Also please see How to Ask. Commented Sep 16, 2022 at 9:54

1 Answer 1

1

This should work:

const arr1 = [
    { id: 1, name: "sai", accounts: ["a"] },
    { id: 2, name: "King", accounts:[] },
    { id: 3, name: "Queen", accounts:["c"] },
    { id: 4, name: "kai", accounts:["e"] },
];

const arr2 = [
    { id: 1, age: 23, accounts: ["b"] },
    { id: 2, age: 24, accounts:[] },
    { id: 3, age: 25, accounts:["d"] }
];

const result = arr1.map((item, i) => Object.assign({}, item, arr2[i]));

New version:

const mergeArrays = () => {
   let res = [];
   
   for (var i = 0; i < arr1.length; i++) {
       let item = arr1[i];
       
       if (arr2[i] && arr1[i].id == arr2[i].id) {
            item.age = arr2[i].age;
            item.accounts = item.accounts.concat(arr2[i].accounts);
       }
       
       res.push(item);
   }
   
   return res;
};
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the quick answer. However, Your answer did merge the array but it didn't merge accounts array inside of array.
This does not seem to merge accounts. Also it assumes the indexes are the same, but the question asks for a merge based on id.
This is exactly what I was looking for, thank you for the new version.
The updated code assumes that every id that exists in both arrays will be found at the same index in both arrays. That may be true for the example data, but if something changes in the data then that assumption may be invalidated, and this code will break.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.