De-dupe NSArray of NSDictionaries based on specific keys
I am attempting to de-dupe an NSArray of NSDictionaries based on specific keys in the dictionaries. What I have looks something like this:
NSDictionary *person1 = [NSDictionary dictionaryWithObjectsAndKeys:@"John", @"firstName", @"Smith", "lastName", @"7898", @"employeeID"];
NSDictionary *person2 = [NSDictionary dictionaryWithObjectsAndKeys:@"Eric", @"firstName", @"Johnson", "lastName", @"1718" @"employeeID"];
NSDictionary *person3 = [NSDictionary dictionaryWithObjectsAndKeys:@"John", @"firstName", @"Smith", "lastName", @"1153", @"employeeID"];
NSMutableArray *personArray = [NSArray arrayWithObjects:person1, person2, person3, nil];
// insert some code to de-dupe personArray based SOLELY on the firstName and lastName keys
Notice how there are two employees with the same name but different ID's. What I would like to do is just get back a new array with only person1 and person2, since person3 has the same data - I just don't care about the "employeeID" value in this 开发者_如何学JAVAparticular problem.
Any ideas? Thanks!
-Matt
Add a Person class which inherits from NSDictionary and implement isEqual: ignoring the ID key, cast your dictionaries to this class, then create an NSSet from your Person objects.
In this very case I would create a temporary NSMutableDictionary and add each personX dictionary as object and its "firstName"'s value as key. This way, a personX dictionary will be replaced if another personX with the same name is added to the temporary. Then get the array from the temporary dictionary with -allValues.
精彩评论