I have a JSON array with three objects. How do I determine if any of them are a duplicate object? I do not need to know which one is duplicated, just if it exists.
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
6
Answers
Regardless of your data structure, I think this will help you to understand how to find that,
You could stringify the objects and then compare:
This link has additional ways to do a deep comparison of objects: https://www.syncfusion.com/blogs/post/5-different-ways-to-deep-compare-javascript-objects.aspx
You can "hash" each item and populate a
Set
. If you detect a hit, there is a duplicate.You can find duplicates like this
dup = arr.filter(obj=> dupId.includes(obj.id));
Here, we determine if there are duplicate objects in a JSON array by utilizing JavaScript’s Set object
If you need speed here, you could manually compare any objects by traversing:
And benchmarking with
JSON.stringify
: