Sometimes, we want to get the difference between two arrays of objects in JavaScript.
In this article, we’ll look at how to get the difference between two arrays of objects in JavaScript.
How to get the difference between two arrays of objects in JavaScript?
To get the difference between two arrays of objects in JavaScript, we can use the array filter method.
For instance, we write
const arrayOne = [
{ value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "alex" },
{ value: "644838b3-604d-4899-8b78-09e4799f586f", display: "james" },
{ value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "jane" },
{ value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "bob" },
{ value: "a63a6f77-c637-454e-abf2-dfb9b543af6c", display: "joe" },
];
const arrayTwo = [
{ value: "4a55eff3-1e0d-4a81-9105-3ddd7521d642", display: "alex" },
{ value: "644838b3-604d-4899-8b78-09e4799f586f", display: "james" },
{ value: "b6ee537a-375c-45bd-b9d4-4dd84a75041d", display: "jane" },
{ value: "e97339e1-939d-47ab-974c-1b68c9cfb536", display: "bob" },
];
const results = arrayOne.filter(
({ value: id1 }) => !arrayTwo.some(({ value: id2 }) => id2 === id1)
);
console.log(results);
to call arrayOne.filter with a callback that checks if any object with the id that’s the same as the item being looped through in arrayOne with arrayTwo.some.
Then we negate that to find the items in arrayOne that’s not in arrayTwo according to the value values.
Conclusion
To get the difference between two arrays of objects in JavaScript, we can use the array filter method.