Efficient way to efficiently merge arrays of objects in JavaScript I have the below scenario where I am trying to merge two arrays of objects.

The current code works, but I am looking for a more efficient way.



var constList = [
  { name: "jack", id: "1", designation: "hr" },
  { name: "mary", id: "2", designation: "it" },
  { name: "john", id: "3", designation: "fin" }
]

var apiList = [
  { name: "jack", id: "1", height: "10" },
  { name: "mary", id: "2", height: "20" }
]

var temp = [];

constList.forEach(x =&gt; {
  apiList.forEach(y =&gt; {
    if (x.id === y.id) {
      temp.push({ ...x,
        ...y
      });
    }
  });
});

console.log(temp);
You can use reduce for this purpose. Group the objects into an aggregate object by some key which we can make a parameter to a function mergeByKey. This function takes any number of object arrays which are then flattened (change flat to [].concat(...objArrs) for better browser compatibility) then reduced into a single object. During grouping, object spreading updates the value for each unique key as you did. Finally, extract the array of values from the grouping object using Object.values which is the final result.

Time complexity of the original version was O((n*longest_obj_length)^2), but the updated version is O(n*longest_obj_length).



const mergeByKey = (key, ...objArrs) =&gt;
  Object.values(objArrs.flat().reduce((a, e) =&gt; {
    a[e[key]] = {...a[e[key]], ...e};
    return a;
  }, {}))
;

const constList = [
  { name: "jack", id: "1", designation: "hr" },
  { name: "mary", id: "2", designation: "it" },
  { name: "john", id: "3", designation: "fin" }
];

const apiList = [
  { name: "jack", id: "1", height: "10" },
  { name: "mary", id: "2", height: "20" }
];

console.log(mergeByKey("id", constList, apiList));