How to remove duplicate values ​​from an array

Hello, I have one NSMUtableArry that contains the value of duplicates, for example [1,2,3,1,1,6]. I want to remove the value of duplicates and I want the new array to have different values. Please, help

+7
source share
6 answers

two liners

NSMutableArray *uniqueArray = [NSMutableArray array]; [uniqueArray addObjectsFromArray:[[NSSet setWithArray:duplicateArray] allObjects]]; 
+18
source

I created a category in NSArray using 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 effective, probably the best approach.

+2
source

My decision:

 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); 

Conclusion: 1,2,3,5,6 ..... I hope it helps you. :)

+2
source

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

 NSSet *set = [NSSet setWithArray:myArray]; 

It will contain only unique objects:

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

0
source

If you are worried about ordering, check out this solution.

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

NSSet's approach is best if you don't care about the order of objects

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

All Articles