The best way to remove duplicate values (NSString
) from NSMutableArray
in Objective-C?
Is this the easiest and right way to do it?
uniquearray = [[NSSet setWithArray:yourarray] allObjects];
In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.
1. If you want to remove all duplicates but leave the highest ones, you can apply this formula =MAX(IF($A$2:$A$12=D2,$B$2:$B$12)), remember to press Shift + Ctrl + Enter keys. 2. In the above formulas, A2:A12 is the original list you need to remove duplicates from.
To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.
Your NSSet
approach is the best if you're not worried about the order of the objects, but then again, if you're not worried about the order, then why aren't you storing them in an NSSet
to begin with?
I wrote the answer below in 2009; in 2011, Apple added NSOrderedSet
to iOS 5 and Mac OS X 10.7. What had been an algorithm is now two lines of code:
NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:yourArray]; NSArray *arrayWithoutDuplicates = [orderedSet array];
If you are worried about the order and you're running on iOS 4 or earlier, loop over a copy of the array:
NSArray *copy = [mutableArray copy]; NSInteger index = [copy count] - 1; for (id object in [copy reverseObjectEnumerator]) { if ([mutableArray indexOfObject:object inRange:NSMakeRange(0, index)] != NSNotFound) { [mutableArray removeObjectAtIndex:index]; } index--; } [copy release];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With