2

I have two object arrays :

first = [
  { "id": "15", "name": "raza" },
  { "id": "1", "name": "sahir" },
  { "id": "54", "name": "ayyan" },
  { "id": "3", "name": "tahir" },
];

 second = [
  { "id": "15", "name": "razi" },
  { "id": "3", "name": "qasim" },
  { "id": "1", "name": "taha" },
];

I want to get unmatched objects from "first" array on the basis of their id, something like

const result = this.first.filter(e => this.second.some(({id}) => e.id ==id ));

It gives me matched objects but I want to get unmatched objects.

0

2 Answers 2

4

Something like this ?

first = [
  { "id": "15", "name": "raza" },
  { "id": "1", "name": "sahir" },
  { "id": "54", "name": "ayyan" },
  { "id": "3", "name": "tahir" },
];

second = [
  { "id": "15", "name": "razi" },
  { "id": "3", "name": "qasim" },
  { "id": "1", "name": "taha" },
];

unmatched = first.filter(item => !second.some(_item => _item.id === item.id));

console.log(unmatched);

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

Comments

0

Here is O(n+m) time complexity solution (n,m are arrays lengths):

let h={}; second.map(x=>h[x.id]=1);     // we use hash map with "second" ids
let result = first.filter(x=>!h[x.id]);

first = [
  { "id": "15", "name": "raza" },
  { "id": "1", "name": "sahir" },
  { "id": "54", "name": "ayyan" },
  { "id": "3", "name": "tahir" },
];

second = [
  { "id": "15", "name": "razi" },
  { "id": "3", "name": "qasim" },
  { "id": "1", "name": "taha" },
];

let h = {}; second.map(x=>h[x.id]=1);     // we use hash map with data2 ids
let result = first.filter(x=>!h[x.id]);

console.log(result);

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.