Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The best way to remove duplicate values from NSMutableArray in Objective-C?

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]; 
like image 519
Teo Choong Ping Avatar asked Jun 22 '09 06:06

Teo Choong Ping


People also ask

How do you remove duplicate records based on values?

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.

How do I remove duplicate rows and keep the highest value only?

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.

How do you remove all duplicates from an array of objects?

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.


1 Answers

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]; 
like image 83
Jim Puls Avatar answered Oct 15 '22 13:10

Jim Puls