30

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
Regexident
  • 29,441
  • 10
  • 93
  • 100
Coocoo4Cocoa
  • 48,756
  • 50
  • 150
  • 175

3 Answers3

62

Just use [newArray addObjectsFromArray:anArray];

Regexident
  • 29,441
  • 10
  • 93
  • 100
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
  • 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. – Coocoo4Cocoa Aug 14 '09 at 19:20
  • 2
    This should still give you a flat array; you're not adding the array, you're adding the objects FROM the array. – Ben Gottlieb Aug 14 '09 at 20:35
  • 1
    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. – Peter Hosey Aug 14 '09 at 22:06
21

-[NSMutableArray addObjectsFromArray:]

Chuck
  • 234,037
  • 30
  • 302
  • 389
  • 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. – drewish Jul 13 '12 at 23:39
20

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.

Kaitain
  • 911
  • 12
  • 19