neel
neel

Reputation: 209

How to remove duplicate values from array

I have one NSMutableArray which containing duplicates value e.g.[1,2,3,1,1,6]. I want to remove duplicates value and want new array with distinct values.

Upvotes: 7

Views: 14045

Answers (6)

Yogesh Kumar
Yogesh Kumar

Reputation: 289

NSSet approach is the best if you're not worried about the order of the objects

 uniquearray = [[NSSet setWithArray:yourarray] allObjects];

Upvotes: 0

keen
keen

Reputation: 3011

If you are worried about the order, check this solution

// iOS 5.0 and later
NSArray * newArray = [[NSOrderedSet orderedSetWithArray:oldArray] array];

Upvotes: 0

REALFREE
REALFREE

Reputation: 4396

two liner

NSMutableArray *uniqueArray = [NSMutableArray array];

[uniqueArray addObjectsFromArray:[[NSSet setWithArray:duplicateArray] allObjects]];

Upvotes: 18

GauravBoss
GauravBoss

Reputation: 140

My solution:

array1=[NSMutableArray arrayWithObjects:@"1",@"2",@"2",@"3",@"3",@"3",@"2",@"5",@"6",@"6",nil];
array2=[[NSMutableArray alloc]init];
for (id obj in array1) 
{
    if (![array2 containsObject:obj]) 
    {
        [array2 addObject: obj];
    }
}
NSLog(@"new array is %@",array2);

The output is: 1,2,3,5,6..... Hope it's help you. :)

Upvotes: 3

Ole Begemann
Ole Begemann

Reputation: 135550

If the order of the values is not important, the easiest way is to create a set from the array:

NSSet *set = [NSSet setWithArray:myArray];

It will only contain unique objects:

If the same object appears more than once in array, it is added only once to the returned set.

Upvotes: 0

deanWombourne
deanWombourne

Reputation: 38475

I've made a category on NSArray with this method in :

- (NSArray *)arrayWithUniqueObjects {
    NSMutableArray *newArray = [NSMutableArray arrayWithCapacity:[self count]];

    for (id item in self)
        if (NO == [newArray containsObject:item])
            [newArray addObject:item];

    return [NSArray arrayWithArray:newArray];
}

However, this is brute force and not very efficient, there's probably a better approach.

Upvotes: 2

Related Questions