0

I have 2 arrays and I want to filter data based on column value. I am using below code but It is not working.

const result = data.map(data1 => {
            return Object.assign({}, data1, this.data2.filter(data2 => data2.Id !== data1.Id)[0]);
        });

Data 1 :

[
  {
    "id": 2,
    "name": "data 2",
  },
  {
    "id": 3,
    "name": "data 3",
  }
]

Data 2 :

[
  {
    "id": 2,
    "name": "data 2"
  },
  {
    "id": 3,
    "name": "data 3"
  },
  {
    "id": 4,
    "name": "data 4"
  }
]

It should return below output.

[
{
    "id": 4,
    "name": "data 4"
}
]

How do I solve this ?

7
  • Can you provide a sample of what are your input arrays are and what output you expect? Commented May 12, 2017 at 16:09
  • @Eeks33 check updated post. Commented May 12, 2017 at 16:19
  • So, you want to keep all the objects in data2 that don't exist in data1 (and use their ID to know if they exist or not in data1), is that right? Commented May 12, 2017 at 16:25
  • @JBNizet, yes. right Commented May 12, 2017 at 16:25
  • Possible duplicate of JavaScript array difference Commented May 12, 2017 at 16:26

1 Answer 1

6

What you're looking for is a difference of 2 arrays of objects, see: Difference between two array of objects in JavaScript

You can also go by pure ids like this:

let ids = data1.map(item => item.id);
let filteredData = data2.filter(item => ids.indexOf(item.id) === -1);
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.