0

I have an array and would like to append N items from another array to it, but only the items not already exist in the current array.

Note, the uniqueness of item is determined not by the object memory but its content. For example, I can have two distinct objects called Person with name "David" and I only one of this in my final result.

What's an efficient way to do this? I have looked at the options of doing it using NSPredicate and NSOrderedSet.

Boon
  • 40,656
  • 60
  • 209
  • 315

2 Answers2

1

[@[arrayOne,arrayTwo] valueForKeyPath:@"@distinctUnionOfArrays.name"] where name is the property to merge the arrays with.

See NSHipster's KVC Collection Operators

stevesliva
  • 5,351
  • 1
  • 16
  • 39
0

Can be easily achieved using NSSet. Here is an example solution:

//Lines of init can be ignored. Just pay attention to the variables and their comments

NSArray * old = [[NSArray alloc]init]; //Assume this is your old array 
NSArray * more = [[NSArray alloc]init]; //Assume this is your extra array
NSArray * new = [[NSArray alloc]init]; //Assume this is your new array (having duplicates)
new = [old arrayByAddingObjectsFromArray:more];
NSArray *cleanedArray = [[NSSet setWithArray:new] allObjects];

For explanation, NSSet automatically removes duplicates.

Warning: It does not preserve the order. If you want to proceed to maintain the order, sort it afterwards, or there are more complex solution on the way.

donkey
  • 4,285
  • 7
  • 42
  • 68
  • I think a thread in http://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objective-c suggests another way using NSOrderedset where you can preserve the order of the array too. But since your task is to append and then eliminate, NSOrderedset might not be helpful as expected. You have to re-sort afterwards anyway. – donkey May 13 '14 at 22:49