What is the Objective-C equivalent of the JavaScript concat()
function?
Assuming that both objects are arrays, how would you combine them?
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.
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.
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With