I am faced with a situation where I must update an existing array by utilizing its chunks to perform a specific operation. While I have a functional solution in place, I am concerned about the performance implications and I am eager to determine if my current approach is optimal.
const parentArray = [
{
key: 0,
customerId: 'customer 0',
partyType: 'party 0',
date: '2020-05-25T17:17:38.910Z',
},
{
key: 1,
customerId: 'customer 1',
partyType: 'party 1',
date: '2020-05-26T17:17:38.910Z',
},
{
key: 2,
customerId: 'customer 2',
partyType: 'party 2',
date: '2020-05-27T17:17:38.910Z',
},
{
key: 3,
customerId: 'customer 3',
partyType: 'party 3',
date: '2020-05-28T17:17:38.910Z',
},
];
const childArray = [
{
key: 1,
customerId: 'customer 01',
partyType: 'party 01',
date: '2020-05-25T17:17:38.910Z',
},
{
key: 3,
customerId: 'customer 21',
partyType: 'party 21',
date: '2020-05-27T17:17:38.910Z',
},
];
const mergeArraysHandler = (parentArray, childArray, key) => {
return parentArray.map((item, i) => {
const record = childArray.find(record => record[key] === item[key]);
if (record) {
return record;
}
else {
return item;
}
});
}
console.log(mergeArraysHandler(parentArray, childArray, 'key'));
As illustrated above, I have developed a method that takes the parent array, child array, and a unique property as inputs to execute the necessary checks. As anticipated, this method merges the two arrays while maintaining the original indexing and updating the parent array accordingly.