0

I have the following Arrays:

A = [
   {
      "id": "111a",
      "week": 2,
      "percentComplete": 50
   },
   {
      "id": "111b",
      "week": 2,
      "percentComplete": 60
   }
]
B = [
   {
      "id": "111a",
      "week": 1,
      "percentComplete": 20
   },
   {
      "id": "111b",
      "week": 1,
      "percentComplete": 30
   },
   {
      "id": "111c",
      "week": 1,
      "percentComplete": 40
   }
]

Expected Output I am trying to merge Array 'A' with array 'B' and create a new array C. Array C will have all the unique objects from 'B' and replace the ones that has common id with updated value from Array 'A'. I tried using set function but it returns all the item, instead of returning the unique ones: C = [...new Set([...A, ...B])]

C = [
   {
      "id": "111a",
      "week": 1,
      "percentComplete": 50
   },
   {
      "id": "111b",
      "week": 1,
      "percentComplete": 60
   },
   {
      "id": "11c",
      "week": 1,
      "percentComplete": 40
   }
]
Vivek Jain
  • 2,730
  • 6
  • 12
  • 27
yellowSub
  • 209
  • 3
  • 12
  • const merged = B.map(bItem => { const aItem = A.find(aItem => aItem.id === bItem.id); return aItem ? aItem : bItem; }); – Lesiak Sep 15 '20 at 22:16

2 Answers2

0

You can try contating them and then filtering out alements that are already in the array

C = A.concat(B).filter((el, i, arr) => arr.findIndex(cEl => cEl.id === el.id) === i);

that will throw away the duplicates

Andrei
  • 10,117
  • 13
  • 21
0

Check the second part of That answer Using ES6 Map.

but for your case, it'll be 'id' instead of 'member'

the snippet should be something like

A = [{
    "id": "111a",
    "week": 2,
    "percentComplete": 50
  },
  {
    "id": "111b",
    "week": 2,
    "percentComplete": 60
  }
]
B = [{
    "id": "111a",
    "week": 1,
    "percentComplete": 20
  },
  {
    "id": "111b",
    "week": 1,
    "percentComplete": 30
  },
  {
    "id": "111c",
    "week": 1,
    "percentComplete": 40
  }
]

const merged = [...A.concat(B).reduce((m, o) =>
  m.set(o.id, Object.assign(m.get(o.id) || {}, o)), new Map()).values()];

console.log(merged)
mbkfa93
  • 126
  • 2
  • 6