0

Let us say I have two arrays like the following:

const arr1 = [
    {id:1, value:25},
    {id:2, value:15},
    {id:3, value:35}
];

const arr2 = [
    {id:3, value:95},
    {id:4, value:65}
];

And I want a third array that includes the 3 items with unique id's, but for the two objects with repeating id's (id:3) - I want to keep the same ID and add the values. Ending up with something like...

const arr3 = [
    {id:1, value:25},
    {id:2, value:15},
    {id:3, value:130},
    {id:4, value:65},
];

So I need the most efficient way to find the objects with the same ID's, then do some logic to merge their values and add the merged object back to the new, combined, array.

Billies Wesley
  • 437
  • 1
  • 6
  • 21
  • what goes wrong? – Nina Scholz Nov 23 '22 at 19:32
  • 1
    `const arr3 = Array.from([ ...arr1, ...arr2 ].reduce((idToSum, { id, value }) => idToSum.set(id, (idToSum.get(id) ?? 0) + value), new Map()), ([ id, value ]) => ({ id, value }));`. – Sebastian Simon Nov 23 '22 at 19:35
  • @NinaScholz - I tried mapping over one of the arrays, and using .includes to find duplicates - but first - i need to compare a property within the objects of the array, not the objects themselves. And second, the arrays may be different lengths. – Billies Wesley Nov 23 '22 at 19:37

1 Answers1

1

You can use a simple js object to keep track of the ids, so you can lookup for an id in O(1) time, like it's already in use or not.

  1. Merge two arrays
  2. Iterate through the merged array and build a dictionary using reduce()
  3. In every iteration look for the id in the dictionary or not. if the id is not present we insert the new key as id and the value as {id, value}. and if the key is present we need to add the previous value with the new value and finally update it.

const arr1 = [ {id:1, value:25}, {id:2, value:15}, {id:3, value:35} ]; 
const arr2 = [ {id:3, value:95}, {id:4, value:65} ];
 
const res = [...arr1, ...arr2].reduce((a, {id, value}) => ({...a, [id]: a[id] ? {id, value: a[id].value + value} : {id, value}}), {});

console.log(Object.values(res));
Asraf
  • 1,322
  • 2
  • 12