I’m trying to get a following target value by using NSPredicate.
But, I’m having difficulty using NSPredicate syntax.
I want to get lastname lists of max age of same names in source data without duplicate.
Please anyone’s help…
NSDictionary *dic1 = [NSDictionary dictionaryWithObjects:@[@"James", @10] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic2 = [NSDictionary dictionaryWithObjects:@[@"Robert", @15] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic3 = [NSDictionary dictionaryWithObjects:@[@"Robert", @10] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic4 = [NSDictionary dictionaryWithObjects:@[@"James", @20] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic5 = [NSDictionary dictionaryWithObjects:@[@"David", @20] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic6 = [NSDictionary dictionaryWithObjects:@[@"Walter", @30] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic7 = [NSDictionary dictionaryWithObjects:@[@"Nicholas", @30] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic8 = [NSDictionary dictionaryWithObjects:@[@"David", @30] forKeys:@[@"LastName", @"Age"]];
NSDictionary *dic9 = [NSDictionary dictionaryWithObjects:@[@"David", @30] forKeys:@[@"LastName", @"Age"]];
NSArray *persons = [NSArray arrayWithObjects:dic1, dic2, dic3, dic4, dic5, dic6, dic7, dic8, dic9, nil];
NSPredicate *predicate = [NSPredicate predicateWithFormat:???]
NSArray *result = [persons filteredArrayUsingPredicate:predicate];
NSLog(@"result : %@",result);
source data
LastName age
James 10
Robert 15
Robert 10
James 20
David 20
Walter 30
Nicholas 30
David 30
David 30
target data
James 20
Robert 15
David 30
Walter 30
Nicholas 30
I don’t believe this can be done with a predicate. I would do it by sorting the array with the key “Age”, and then looping through that array, adding the first record to a results array, then checking whether the next record has the same LastName as the first, and if so don’t add that one to the final array. Like this: