0

how can i merge these to arrays togheter, if there is a duplicate in id: i want to add them together

const arr1 = [{id:'1', start:1, end:0},{id:'2', start:3, end:0},{id:'3', start:1, end:0}]

const arr2 = [{id:'4', start:0, end:4},{id:'2', start:0, end:4}]

i want the output to be like this

const arr3 =[{id:'1', start:1, end:0},{id:'2', start:3, end:4},{id:'3', start:1, end:0},
{id:'4', start:0, end:4}]

I am new here and grateful for all the help! :)

doğukan
  • 23,073
  • 13
  • 57
  • 69
  • Does this answer your question? [How to merge two arrays in JavaScript and de-duplicate items](https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items) – dale landry Mar 21 '21 at 21:04

3 Answers3

0

Check this:

// merge both arrays
const mergedArr = arr1.concat(arr2);

// filter items that only arr2 have
const onlyAtArr2 = arr2.filter(i2 => !arr1.find(i1 => i1.id === i2.id));

// map their values
const arr3 = arr1.concat(onlyAtArr2).map((item) => {
  return {
   id: item.id,
   start: mergedArr.filter(i => i.id === item.id).reduce((a,b) => a + (b.start || 0), 0),
   end: mergedArr.filter(i => i.id === item.id).reduce((a, b) => a + (b.end|| 0), 0),
  };
});

// display value
console.log(arr3);

0: Object { id: "1", start: 1, end: 0 }
1: Object { id: "2", start: 3, end: 4 }
2: Object { id: "3", start: 1, end: 0 }
3: Object { id: "4", start: 0, end: 4 }
Arthur Borba
  • 403
  • 3
  • 16
0

I think this would be easier if arr1 and arr2 where maps instead of arrays, assuming id is unique:

const map1 = new Map(arr1.map(x => [x.id, {start: x.start, end: x.end}]))
const map2 = new Map(arr2.map(x => [x.id, {start: x.start, end: x.end}]))

const intersection = [...map1.keys()].filter(x => map2.has(x))

const map3 = new Map([...map1, ...map2])
intersection.forEach(key => map3.set(key, {start: map1.get(key).start + map2.get(key).start, end: map1.get(key).end + map2.get(key).end}))

console.log(map3)
​
0: 1 → Object { start: 1, end: 0 }
​1: 2 → Object { start: 3, end: 4 }
2: 3 → Object { start: 1, end: 0 }
​​3: 4 → Object { start: 0, end: 4 }
Kevin
  • 3,096
  • 2
  • 8
  • 37
0

https://jsfiddle.net/2j8eazkr/

const arr1 = [{id:'1', start:1, end:0},{id:'2', start:3, end:0},{id:'3', start:1, end:0}]

const arr2 = [{id:'4', start:0, end:4},{id:'2', start:0, end:4}]

//clone elements of first array
let arr3 = arr1.map(x => { return { id: x.id, start: x.start, end: x.end } });

//iterate second array and use it to update existing or add if its new
arr2.forEach(x => {
    
  let y = arr3.find(_ => _.id === x.id);

  if(y) y.end = x.end;
  else arr3.push(x);
  
})
Rex Henderson
  • 412
  • 2
  • 7