Reputation: 429
Hi I have two arrays one has 200 + objects ( never changes) and another which is an array of integers ( as NSNumber objects) what is the easiest way to create a third array which will be an array of all objects from array 1 that are included in the array of indexes from array 2?
Upvotes: 0
Views: 247
Reputation: 40201
One option would be to convert the array of indexes to an NSIndexSet
and then use objectsAtIndexes:
NSArray *objects = @[@"A", @"B", @"C", @"D", @"E", @"F", @"G"];
NSArray *indexArray = @[@(0), @(2), @(6)];
NSMutableIndexSet *indexSet = [NSMutableIndexSet indexSet];
for (NSNumber *number in indexArray) {
[indexSet addIndex:[number unsignedIntegerValue]];
}
NSArray *filtered = [objects objectsAtIndexes:indexSet];
Result: A, C, G
Of course, if you can, it would be better to directly use an index set, instead of an array.
Or you could just use a simple loop.
NSMutableArray *filtered = [[NSMutableArray alloc]
initWithCapacity:indexArray.length];
for (NSNumber *number in indexArray) {
[filtered addObject:objects[[number unsignedIntegerValue]]];
}
Upvotes: 2
Reputation: 38728
You can create sets and use the methods on NSMutableSet
NSArray *array1 = @[ @1, @2, @3 ];
NSArray *array2 = @[ @2 ];
NSMutableSet *set = [NSMutableSet setWithArray:array1];
[set intersectSet:[NSSet setWithArray:array2]];
NSLog(@"%@", set.allObjects);
//=>( 2 )
Upvotes: 1