Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn an NSArray of strings into an array of unique strings, in the same order?

If you have an NSArray of strings

{ @"ONE", @"ONE", @"ONE", "TWO", @"THREE", @"THREE" }

How would I turn that into

{ @"ONE", @"TWO", @"THREE" }

..where the array follows the same order as the original. I think that you can turn an array into an NSSet to get unique items, but if you turn it back into an array you are not guaranteed to get the same order..

like image 238
cannyboy Avatar asked Nov 17 '10 22:11

cannyboy


3 Answers

My initial thought was that you could do:

NSArray * a = [NSArray arrayWithObjects:@"ONE", @"ONE", @"ONE", @"TWO", @"THREE", @"THREE", nil];
NSLog(@"%@", [a valueForKeyPath:@"@distinctUnionOfObjects.self"]);

But that does not maintain order. Therefore, you have to do it manually:

NSArray * a = [NSArray arrayWithObjects:@"ONE", @"ONE", @"ONE", @"TWO", @"THREE", @"THREE", nil];
NSMutableArray * unique = [NSMutableArray array];
NSMutableSet * processed = [NSMutableSet set];
for (NSString * string in a) {
  if ([processed containsObject:string] == NO) {
    [unique addObject:string];
    [processed addObject:string];
  }
}

I use an NSMutableSet for determining if I've already come across this entry before (as opposed to [unique containsObject:string], since a set will have O(1) lookup time, and an array has O(n) lookup time. If you're only dealing with a small number of objects, then this won't matter. However, if the source array is very large, then using the set to determine uniqueness may add a bit of a speed boost. (however, you should use Instruments to profile your code and see if it's necessary)

like image 82
Dave DeLong Avatar answered Nov 05 '22 09:11

Dave DeLong


You could do like this:

NSArray * uniqueArray = [[NSOrderedSet orderedSetWithArray:duplicatesArray] array];

This way, you also preserve the order!

like image 49
Santhos Ramalingam Avatar answered Nov 05 '22 08:11

Santhos Ramalingam


I Think You can Do this With that

NSArray * uniqueArray = [[Yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"] sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];

i hope this would help you

like image 7
umer sufyan Avatar answered Nov 05 '22 08:11

umer sufyan