Search code examples
javascriptarraysarray-merge

Is there a way to merge two nested array based on common key


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

Solution

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