Search code examples
iosobjective-carraysduplicatesnsarray

Remove duplicate items from array and keep last occurrences - iOS


I have an array, as

(one, two, one, two, three, one, three, two)

I want to remove duplicates, and keep last occurrences of items only. my result array should be:

(one, three, two)

I achieved removing duplicates by [NSOrderedSet orderedSetWithArray:array] but this keeps first occurrences of items. the result it gives is (one, two, three) i.e. 1st index, 2nd index and 5th index.

How can I keep last occurrences only, so my result should be 6th index, 7th index, and 8th index?

Thanks!


Solution

  • Thanks for the right direction @Avi and @Cristik (commenters on the question) , implemented the following solution and its working:

    NSMutableArray *array = [NSMutableArray arrayWithCapacity:[originalArray count]];
    NSEnumerator *enumerator = [originalArray reverseObjectEnumerator];
    
    for (id element in enumerator) 
    {
       [array addObject:element];
    }
    
    NSOrderedSet *orderedSet =  [NSOrderedSet orderedSetWithArray:array];
    
    /* orderedSet now has has the desired result */