Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would I combine two arrays in Objective-C?

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

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

like image 218
Moshe Avatar asked Jan 19 '11 22:01

Moshe


People also ask

How do I combine two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

Which method is used to combine elements of 2 arrays?

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.


1 Answers

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]; 
like image 100
grahamparks Avatar answered Sep 29 '22 07:09

grahamparks