Merging NSArrays in Objective-C
Solution 1
Just use [newArray addObjectsFromArray:anArray];
Solution 2
-[NSMutableArray addObjectsFromArray:]
Solution 3
There is some confusion in Benn Gottlieb's answer above. To clarify, he is suggesting using addObjectsFromArray instead of the inner loop, whereas Coocoo is confused because he thinks it is being suggested as a replacement for ALL the looping. (If you do this, you will indeed be left with an unflattened array of arrays as per his objection.)
Here is a reasonably elegant solution that doesn't require any explicit looping:
NSArray *anArray = [someDictionary allValues];
NSArray *flattenedArray = [anArray valueForKeyPath: @"@unionOfArrays.self"];
btw this code will leave duplicates in the flattened array. If you want to remove duplicates, use distinctUnionOfArrays instead of unionOfArrays.
Roman
Updated on June 05, 2022Comments
-
Roman almost 2 years
I have an NSDictionary where each key points to an array. I later want to merge all of the values into one array. Is there a way to use the API to do something more efficient than say:
NSArray *anArray = [someDictionary allValues]; NSMutableArray *newArray = [NSMutableArray array]; start outter loop on anArray start inner loop on objects in anArray add objectAtIndex to newArray
-
Roman over 14 yearsHi Ben, If I do it this way I don't have a flat array. I have an array of arrays. I was seeing if it was possible to do it without the looping.
-
Ben Gottlieb over 14 yearsThis should still give you a flat array; you're not adding the array, you're adding the objects FROM the array.
-
Nico over 14 yearsCoocoo4Cocoa: I think you've confused
addObject
**FromArray:
** withaddObject:
.addObject:
adds the array to the new array, whereas what Chuck and Ben Gottlieb have suggested adds the elements in the array to the new array. -
drewish almost 12 yearsI'm glad someone pointed out the class type. I'd sat there for a second wondering why the method wasn't being auto-completed.
-
Cezar about 10 yearsToday, this is a better solution than all of the above.