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);

Mast
13.8k12 gold badges56 silver badges127 bronze badges
asked Dec 18, 2019 at 15:51
\$\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\$ Commented Dec 18, 2019 at 16:05
  • 1
    \$\begingroup\$ They are consecutive but there could be gaps. \$\endgroup\$ Commented Dec 18, 2019 at 16:09

1 Answer 1

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));

answered Dec 18, 2019 at 16:32
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.