filter duplicate from NSArray using object property
ios, nsarray, objective-c
Solution
First of all thank you all for all your tips, this is how I was able to solve my problem:
-( NSArray *) filterOutDuplicateOrder: (NSArray *)unFilteredArray
{
// First sort array by descending so I could capture the max id
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"itemID" ascending:NO];
NSArray *sortedDescArray = [unFilteredArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
// Filter out duplicates using typeID
NSMutableArray *filteredArrayOfObjects = [[NSMutableArray alloc] init];
for (Order *order in sortedDescArray)
{
if(!([[filteredArrayOfObjects valueForKeyPath:@"typeID"] containsObject:order.typeID]))
{
[filteredArrayOfObjects addObject:progressNote];
}
}
return resultArray;
}
Problem
I have an NSArray which contains list of Order objects, an Order object has three properties ( id, typeID and description), I want to filter my array based on typeID to exclude duplicates. Duplicates are determined by typeID e.g if there are 2 items with typeID=7 then I want to pick the Order which has the max id so in this case it would be => id=2. My src Array with Order objects: ``` Item 1: id=1, typeID=7, description="some text 1" Item 2: id=2, typeID=7, description="some text 2" Item 3: id=3, typeID=5, description="some text 3" Item 4: id=4, typeID=5, description="some text 4" Item 5: id=5, typeID=8, description="some text 5" ``` After applying filter my returned array should look likefollowing: ``` Item 2: id=2, typeID=7, description="some text 2" Item 4: id=4, typeID=5, description="some text 4" Item 5: id=5, typeID=8, description="some text 5" ``` Can someone suggest what would be the best way to do this, thanks.