Merging NSArrays in Objective-C

19,204

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.

Share:
19,204
Roman
Author by

Roman

Updated on June 05, 2022

Comments

  • Roman
    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
    Roman over 14 years
    Hi 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
    Ben Gottlieb over 14 years
    This should still give you a flat array; you're not adding the array, you're adding the objects FROM the array.
  • Nico
    Nico over 14 years
    Coocoo4Cocoa: I think you've confused addObject**FromArray:** with addObject:. 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
    drewish almost 12 years
    I'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
    Cezar about 10 years
    Today, this is a better solution than all of the above.