78

What is the Objective-C equivalent of the JavaScript concat() function?

Assuming that both objects are arrays, how would you combine them?

2
  • It looks like you're doing calendrical operations. Please consider using NSCalendar and NSDateComponents and friends to do them for you. They are not a trivial subject. Are you taking leap months into account? How about daylight savings time? What about leap seconds? etc. Commented Jan 19, 2011 at 22:53
  • @DaveDeLong - Right now I'm porting a small Javascript Library. I will be refactoring code once I'm done with the actual rewrite. My first goal is to get the information in Objective-C and optimize later. Commented Jan 19, 2011 at 22:55

2 Answers 2

221

NSArray's arrayByAddingObjectsFromArray: is more-or-less equivalent to JavaScript's .concat() method:

NSArray *newArray=[firstArray arrayByAddingObjectsFromArray:secondArray];

Note: If firstArray is nil, newArray will be nil. This can be fixed by using the following:

NSArray *newArray=firstArray?[firstArray arrayByAddingObjectsFromArray:secondArray]:[[NSArray alloc] initWithArray:secondArray];

If you want to strip-out duplicates:

NSArray *uniqueEntries = (NSArray *)[[NSSet setWithArray:newArray] allObjects];
Sign up to request clarification or add additional context in comments.

8 Comments

Would this require an firstArray to be an NSMutableArray?
@Moshe It returns a new (immutable) NSArray object, and doesn't alter the original array, so it works fine on NSArray objects.
There is a potential problem with the answer, if the firstArray is nil but the second array is not, the newArray is nil.
Sure, then add: if (!firstArray) firstArray = @[ ];
then to make sure that you only get unique entries (if that's what you want): NSArray *uniqueEntries = [[NSSet setWithArray:newArray] allObjects];
|
10

Here's a symmetric & simple way by just beginning with an empty array:

NSArray* newArray = @[];
newArray = [newArray arrayByAddingObjectsFromArray:firstArray];
newArray = [newArray arrayByAddingObjectsFromArray:secondArray];

Comments

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.