I am struggling with comparing two arrays of objects based on a key.
My goal is to compare the values, subtracting them when the keys match and displaying negative values for those not found in my target array. Additionally, I want to include all target objects that do not have matching keys in my final array.
An example can illustrate this scenario better:
const initial = [{id: 1, value: 47}, {id: 2, value: 20}, {id: 7, value: 13}];
const target = [{id: 1, value: 150}, {id: 3, value: 70}, {id: 40, value: 477}];
// Desired output
// [{id: 1, value: 103}, {id: 2, value: -20}, {id: 7, value: -13}, {id: 3, value: 70}, {id: 40, value: 477}];
let comparator = [];
initial.map(initia => {
let hasSame = target.find(targ => {
return initia.id === targ.id;
});
if(hasSame) {
initia.value -= hasSame.value;
} else{
initia.value = -initia.value;
}
});
console.log(initial);
I have almost achieved the desired result, but I am unsure how to properly merge the target values. Is there a way to accomplish this without iterating through the target array again? Can it be done within the find method?
I would appreciate any advice or guidance on achieving this task efficiently.
Thank you!