Search code examples
objective-ccocoa

How can I most easily flatten a three-dimensional array in Cocoa?


Say I have an array such as this:

NSArray *threeDimensionalArray = @[
 @[     
     @[ @"Peter", @"Paul", @"Mary" ], @[ @"Joe", @"Jane" ]
  ],
 @[
     @[ @"Alice", @"Bob" ]
  ]
];

and I want it to become:

@[ @"Peter", @"Paul", @"Mary", @"Joe", @"Jane", @"Alice", @"Bob" ]

How can I most easily create this flattened array?


Solution

  • The key-value coding (KVC) collection operator @unionOfArrays flattens one level of arrays, so applying it twice produces the desired result.

    Collection operators (other than @count) need a key path to a collection property, and since our objects are already arrays (and hence collections) in themselves, the key path will have to be self.

    We therefore need to apply @unionOfArrays twice with the self key path, yielding the following KVC call to flatten a 3D array:

    NSArray *flattenedArray = [threeDimensionalArray valueForKeyPath: @"@unionOfArrays.self.@unionOfArrays.self"];