IPhone sdk: how to remove duplicates in NSArray

Hi, my NSArray contains duplicates like this (I need to remove duplicates)

Titles: Father's Day

Titles: Father's Day

Titles: Father's Day

Titles: Election Day

Titles: Election Day

Titles: Election Day

titles: Easter

titles: Easter

Names: Earth Day

Names: Earth Day

Names: Earth Day

titles: Cinco de Mayo

titles: Cinco de Mayo

titles: Cinco de Mayo

titles: Christmas Eve

titles: Christmas Eve

titles: Christmas Eve

Titles: Christmas Names: Christmas Names: Christmas

I have only one name and no other duplicates are needed. how am I doing this, please help me with a clear explanation to solve this problem. Thanks.

+1
source share
3 answers

If you want to arrange, you can create a new mutable array, skip every object in the old array and only add it if it does not exist yet:

NSMutableArray *uniqueItems = [NSMutableArray array]; for (id item in allItems) if (![uniqueItems containsObject:item]) [uniqueItems addObject:item]; 

If not, it’s much easier to just use a set:

 NSSet *uniqueItems = [NSSet setWithArray:allItems]; 
+7
source

Is your NSArray you want to delete already sorted? This is similar to your question. In this case, the following code will be executed:

 NSMutableArray *uniqueItems = [NSMutableArray array]; id lastSeenUniqueObject = nil; for (NSObject *item in allItems) { if (![item isEqual:lastSeenUniqueObject]) { [uniqueItems addObject:item]; lastSeenUniqueObject = item; } } 

It has a N (i.e. fast) runtime complexity, compared to (approximate) N ^ 2 rpetrich answer complexity.

If you do not know that the contents of the array are sorted, you have two options:

A) just sort it and then apply the above algorithm, which gives n log n complexity of execution (even better than N ^ 2),

or

B) Use an NSMutableSet to track objects already seen (or any other data structure using buckets and hashing). The code will look like this:

 NSMutableArray *uniqueItems = [NSMutableArray array]; NSMutableSet *seenItems = [NSMutableSet set]; for (NSObject *item in allItems) { if (![seenItems containsObject:item]) { [uniqueItems addObject:item]; [seenItems addOBject:item]; } } 

It also gives runtime better than N ^ 2.

+2
source

See this simple.

 NSMutableArray *dateArray = [[NSMutableArray alloc]initWithObjects:@"December 29,2010", @"December 28,2010", @"December 22,2010", @"December 22,2010", @"December 22,2010",@"December 21,2010",@"December 28,2010",nil]; 

for Avoid Duplicate use this ...

 NSSet *cleanedArray = [NSSet setWithArray:dateArray]; NSArray *array = [[NSArray alloc]initWithArray:[cleanedArray allObjects]]; for (int i=0; i<[array count]; i++) { NSLog(@"The Given Array is %@",[array objectAtIndex:i]); } 
0
source

All Articles