Reputation: 58642
I have these 2 arrays of objects.
Sorry that I post the image because I want you guys to quickly understand my points.
What is the best way to compare 2 arrays of objects and look for what is not in it?
I can do 2 levels for loops and an if-check, but I'm not sure if it is the best approach. I am seeking a better performance JS way to achieve something like this.
This is what I am looking to extract while comparing arr1
& arr2
.
{
"id": 4,
"name": "Date and Time"
}
Upvotes: 1
Views: 119
Reputation: 27192
Different ways to achieve this requirement. I also created a performance check based on all the below 3 solutions here. Kindly run this test suite and based on the result you can use any of the below solution in your project.
const arr1 = [{
id: 1,
name: "Weather"
}, {
id: 2,
name: "Geo Location"
}, {
id: 3,
name: "Device"
}];
const arr2 = [{
id: 1,
name: "Weather"
}, {
id: 2,
name: "Geo Location"
}, {
id: 3,
name: "Device"
}, {
id: 4,
name: "Date and Time"
}];
const res = arr2.filter((obj) => !arr1.find(({ id }) => obj.id === id));
console.log(res);
const arr1 = [{
id: 1,
name: "Weather"
}, {
id: 2,
name: "Geo Location"
}, {
id: 3,
name: "Device"
}];
const arr2 = [{
id: 1,
name: "Weather"
}, {
id: 2,
name: "Geo Location"
}, {
id: 3,
name: "Device"
}, {
id: 4,
name: "Date and Time"
}];
const IDArray = arr1.map(obj => obj.id);
const res = arr2.filter(obj => !IDArray.includes(obj.id));
console.log(res);
const arr1 = [{
id: 1,
name: "Weather"
}, {
id: 2,
name: "Geo Location"
}, {
id: 3,
name: "Device"
}];
const arr2 = [{
id: 1,
name: "Weather"
}, {
id: 2,
name: "Geo Location"
}, {
id: 3,
name: "Device"
}, {
id: 4,
name: "Date and Time"
}];
const res = arr2.filter(({ id }) => !arr1.some(x => x.id == id))
console.log(res)
Upvotes: 2
Reputation: 23654
One way is to concatenate both arrays together, then iterate and filter to see if that id exists in both arrays. If it doesn't exist in both arrays, it's extra.
a1.concat(a2).filter(a => a1.findIndex(f => f.id === a.id) == -1 || a2.findIndex(f => f.id === a.id) == -1)
let arr1 = [{"id": 1,"name": "Date and Time"},{"id": 2,"name": "Date and Time"},{"id": 3,"name": "Date and Time"},{"id": 4,"name": "Date and Time"}]
let arr2 = [{"id": 1,"name": "Date and Time"},{"id": 2,"name": "Date and Time"},{"id": 3,"name": "Date and Time"}]
const findMissing = (a1, a2) => a1.concat(a2).filter(a => a1.findIndex(f => f.id === a.id) == -1 || a2.findIndex(f => f.id === a.id) == -1)
console.log(findMissing(arr1, arr2))
Upvotes: 2