Search code examples
iossortingduplicatesnsarray

Append arrays and remove duplicates without order change in objective c


Consider I have three arrays.

NSArray *array1 = @[@"4",@"3",@"2"];
NSArray *array2 = @[@"2",@"1"];
NSArray *array3 = @[@"3",@"1",@"5",@"2"];

I want to append these arrays. Conditions are:

  • Order should not change. Means, Array1's order has high priority than Array2.
  • Duplicate values should be removed (When appending Array2 with Array1, I want to remove duplicate values from Array2)

So I expect the result as like:

@[@"4",@"3",@"2",@"1",@"5"];

Question:

  • Should I iterate each and every values to construct the expected result? Is there any simple way to achieve it?

Thanks


Solution

  • You can use NSMutableOrderedSet to achieve this:

    NSMutableOrderedSet *mSet = [NSMutableOrderedSet new];
    [mSet addObjectsFromArray:array1];
    [mSet addObjectsFromArray:array2];
    [mSet addObjectsFromArray:array3];
    NSArray *array = [mSet array];