Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 584
neel Avatar asked Apr 14 '11 10:04

neel


People also ask

How do I remove a repeated value from an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.


2 Answers

two liner

NSMutableArray *uniqueArray = [NSMutableArray array];

[uniqueArray addObjectsFromArray:[[NSSet setWithArray:duplicateArray] allObjects]];
like image 102
REALFREE Avatar answered Sep 24 '22 07:09

REALFREE


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. :)

like image 39
GauravBoss Avatar answered Sep 21 '22 07:09

GauravBoss