mag725
mag725

Reputation: 705

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 particular problem.

Any ideas? Thanks!

-Matt

Upvotes: 0

Views: 398

Answers (2)

w-m
w-m

Reputation: 11232

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.

Upvotes: 5

sigsegv
sigsegv

Reputation: 457

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.

Upvotes: 0

Related Questions