Sometimes, we want to compare two arrays of objects, and exclude the elements who match values into new array in JavaScript.
In this article, we’ll look at how to compare two arrays of objects, and exclude the elements who match values into new array in JavaScript.
How to compare two arrays of objects, and exclude the elements who match values into new array in JavaScript?
To compare two arrays of objects, and exclude the elements who match values into new array in JavaScript, we use the array filter
and some
methods.
For instance, we write
const result = result1.filter((o1) => !result2.some((o2) => o1.id === o2.id));
to call filter
with a callback that calls result2.some
to check if anything in result1
matches the id
in any object in result2
.
If that’s false
, then we put the object o1
in the returned array.
Conclusion
To compare two arrays of objects, and exclude the elements who match values into new array in JavaScript, we use the array filter
and some
methods.