4
\$\begingroup\$

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 => {
  apiList.forEach(y => {
    if (x.id === y.id) {
      temp.push({ ...x,
        ...y
      });
    }
  });
});

console.log(temp);

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Welcome to CR! Are your array ids guaranteed to be sorted sequentially ascending and without gaps as they are in this example? \$\endgroup\$ – ggorlen Dec 18 '19 at 16:05
  • 1
    \$\begingroup\$ They are consecutive but there could be gaps. \$\endgroup\$ – user804401 Dec 18 '19 at 16:09
1
\$\begingroup\$

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) =>
  Object.values(objArrs.flat().reduce((a, e) => {
    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));

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.