How would I combine two arrays in Objective-C?

IosObjective C

Ios Problem Overview


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

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

Ios Solutions


Solution 1 - Ios

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];

Solution 2 - Ios

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMosheView Question on Stackoverflow
Solution 1 - IosgrahamparksView Answer on Stackoverflow
Solution 2 - Iosmeaning-mattersView Answer on Stackoverflow