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.

6
  • 1
    sounds like you want to use NSSet, NSOrderedSet and the mutable counterparts. Commented May 13, 2014 at 22:18
  • @vikingosegundo - Would that work to filter unique objects like he's asking. Objects that aren't duplicates in memory, but are duplicates based on matched properties? Commented May 13, 2014 at 22:30
  • just override isEqual: in Person and it should be good Commented May 13, 2014 at 22:32
  • sure, if equability is implemented correctly. nshipster.com/equality Commented May 13, 2014 at 22:33
  • @vikingosegundo - Thanks for the article, and the clarification ... good stuff. Commented May 13, 2014 at 22:46

2 Answers 2

1

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

See NSHipster's KVC Collection Operators

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

I think a thread in stackoverflow.com/questions/1025674/… 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.