Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing duplicates from NSMutableArray

I have this problem with removing duplicate objects from an array. I tried these already:

noDuplicates = _personalHistory.personalHistory;

for (int i=[noDuplicates count]-1; i>0; i--) {
    if ([noDuplicates indexOfObject: [noDuplicates objectAtIndex: i]]<i)
        [noDuplicates removeObjectAtIndex: i];
}


for (PersonalHistory_artikels *e in _personalHistory.personalHistory) {
    if (![noDuplicates containsObject:e]) {
        NSLog(@"Dubplicates");
        [noDuplicates addObject:e];
    }
}


for (i=0; i<_personalHistory.personalHistory.count; i++) {
    PersonalHistory_artikels *test = [_personalHistory.personalHistory objectAtIndex:i];
    for (j=0; j<_personalHistory.personalHistory.count; j++) {
        PersonalHistory_artikels *test2 = [_personalHistory.personalHistory objectAtIndex:j];
        if (! [test.nieuwsTITLE_personal isEqual:test2.nieuwsTITLE_personal]) {
            NSLog(@"Add test = %@", test.nieuwsTITLE_personal);
            [noDuplicates addObject:test];
        }
    }
}

But none of the above gave me the right array. The last one was the best, but it still showed duplicate values. Can someone help me with this problem? Thank you very much.

like image 201
user750079 Avatar asked Nov 26 '22 20:11

user750079


2 Answers

Just convert the array to an NSSet and back again. A set can't have duplicates by design.

EDIT:

Note that a set doesn't have a sorting order. Therefore, you can go cheaper and forgo the order, or go for a slightly more expensive operation but keep the order.

NSArray *hasDuplicates = /* (...) */;
NSArray *noDuplicates = [[NSSet setWithArray: hasDuplicates] allObjects];
like image 133
Alexsander Akers Avatar answered Dec 30 '22 07:12

Alexsander Akers


In OS X 10.7 and iOS 5.0 and later:

newArray = [[NSOrderedSet orderedSetWithArray:oldArray] array];
like image 45
hatfinch Avatar answered Dec 30 '22 07:12

hatfinch