67

Is there any convenient way to take an array/set of objects and create a new array/set containing some property of each item in the first array?

For example, an array contains Car objects. I need an array of licensePlates, where each car has an NSObject car.licensePlate.

Currently I just iterate through the first array adding objects to my mutable results array, but was wondering if there is an instantiation method that exists for this (checked the docs for NSArray).

Ben Packard
  • 26,102
  • 25
  • 102
  • 183

1 Answers1

119

This will return an array containing the value of licensePlate from each item in the myCars array:

NSArray *licensePlates = [myCars valueForKeyPath:@"licensePlate"]

If you want only unique items (for example), you can do something like this:

NSArray *licensePlates = [myCars valueForKeyPath:@"@distinctUnionOfObjects.licensePlate"];

For more possibilities, see the Collection Operators documentation in the Key-Value Coding Programming Guide.

Mike Weller
  • 45,401
  • 15
  • 131
  • 151
  • I think the operator @unionOfObjects should be used in the first instance. – Francesco Puglisi Jan 31 '14 at 17:06
  • 1
    Great answer! Looks like the link to docs is not working anymore. Here is the right link : https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueCoding/CollectionOperators.html – prad Mar 21 '17 at 06:13