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
1

3 Answers 3

62

Just use [newArray addObjectsFromArray:anArray];

3
  • 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. Aug 14, 2009 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. Aug 14, 2009 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. Aug 14, 2009 at 22:06
21

-[NSMutableArray addObjectsFromArray:]

1
  • 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, 2012 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.

1
  • 6
    Today, this is a better solution than all of the above.
    – Cezar
    Mar 13, 2014 at 15:34

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.