简体   繁体   中英

JS: Compare objects of arrays and delete duplicates

I have two arrays with objects:

var oldUsers = [{"name": "Sam", "ext": 12}, {"name": "John", "ext": 15}];
var newUsers = [{"name": "John", "ext": 15}, {"name": "Jim", "ext": 19}];

Now I want to remove objects from both arrays, which are in both arrays. In this example, I am trying to remove {"name": "John", "ext": 15} from both arrays. Both arrays are containing 200 or more objects, and in the end I need to process the objects which are not deleted, so at the end my arrays have to look like this:

var oldUsers = [{"name": "Sam", "ext": 12}];
var newUsers = [{"name": "Jim", "ext": 19}];

Does anyone of you have an idea how to solve this problem for example by looping through the arrays? I need to compare arrays with a lots of objects and then want to delete duplicate entries with splice() or something like that from both arrays.

Thanks in advance!

It's better to create a set of keys (eg built as "<name>:<ext>" , depending on what's unique) for all items found in one array and traverse the other array checking for the presence. Then run the same thing for the arrays "swapped".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM