2

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.

2
  • 2
    First, write or find a routine to take the difference of two sets, based on some equality function. Then, write the equality function for your case. Commented Aug 1, 2016 at 13:53
  • I thought about it, but im was looking for a simpler way. I will do as you said Commented Aug 1, 2016 at 14:00

1 Answer 1

4

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.