DiegoAugusto
DiegoAugusto

Reputation: 219

Get diff between two arrays of objects with ES6 or TypeScript

I have the following arrays:

  arr1 = [{
      id: 1,
      name: 'Diego',
      age: 23
  }, {
      id: 2,
      name: 'Brian',
      age: 18
  }]

  arr2 = [{
      id: 1,
      name: 'Diego',
      age: 23
  }, {
      id: 2,
      name: 'Brian',
      age: 18
  }, {
      id: 3,
      name: 'Pikachu',
      age: 88
  }]

I need get difference between this two arrays, the espected result is:

arr3 [{id:3, name: 'Pikachu', age: 88}]

How do i solve this problem using ES6 or TypeScript?

I tried using SET, but doesn't worked.

Upvotes: 2

Views: 3505

Answers (1)

Nitzan Tomer
Nitzan Tomer

Reputation: 164257

Something like this maybe:

let ids1 = arr1.map(item => item.id);
let ids2 = arr2.map(item => item.id);

let diff = ids1.map((id, index) => {
        if (ids2.indexOf(id) < 0) {
            return arr1[index];
        }
    }).concat(ids2.map((id, index) => {
        if (ids1.indexOf(id) < 0) {
            return arr2[index];
        }
    })).filter(item => item != undefined);

(code in playground)

Upvotes: 4

Related Questions