-1

I have 2 tables that look like this:

const array = [
  { id: "1", count: 75 },
  { id: "4", count: 32 }
];
const arrayFull = [
  { id: "1", count: 0 },
  { id: "2", count: 0 },
  { id: "3", count: 0 },
  { id: "4", count: 0 }
];

I want to check if the id of the objects of the arrayFull equals with the id of the objects of array. If they are not equal, I want to add the other object items. So in my example, the result should be:

const array = [
  { id: "1", count: 75 },
  { id: "2", count: 0 },
  { id: "3", count: 0 },
  { id: "4", count: 32 }
];

How can I do this? I tried with indexOf() and forEach() and did not work. I am using "target": "es2015".

Nicholas Tower
  • 72,740
  • 7
  • 86
  • 98
Kathrine Hanson
  • 575
  • 2
  • 10
  • 32

1 Answers1

1

You can simply utilise a Set, and use forEach to check if the set has the id on each iteration:

const array = [{id:"1", count: 75},{id:"4", count: 32}];
const arrayFull = [{id:"1", count: 0}, {id:"2", count: 0}, {id:"3", count: 0}, {id:"4", count: 0}];

const set = new Set(array.map(v => v.id))

arrayFull.forEach(v => set.has(v.id) || array.push(v))

console.log(array.sort((a, b) => +a.id - +b.id))

If you didn't want to mutate the original array, you could use reduce with a map:

const array = [{id:"1", count: 75},{id:"4", count: 32}];
const arrayFull = [{id:"1", count: 0}, {id:"2", count: 0}, {id:"3", count: 0}, {id:"4", count: 0}];

const out = [...arrayFull.reduce((a, v) => (a.has(v.id) || a.set(v.id, v), a), new Map(array.map(v => [v.id, v]))).values()]

console.log(out)

Since both of these solutions utilise sets and maps, the time-complexity for each of them will be O(n), as there are no nested loops.

Kobe
  • 6,226
  • 1
  • 14
  • 35