0

So basically I have a huge array of arrays (only a 2-d array)...

My root array lets say has 100 child arrays...

I want to query the root/child arrays and return only the child arrays that have its 2 object equal to hello...

So basically I have a made-up idea below...

updatedArray = [rootArray WHERE childArray objectAtIndex:2 == @"hello"];

Now as you can see I want updated array to contain like 40 or 50 of the child arrays in the rootArray...

See what I mean - its kind of like MySQL only with an array instead of a database?

ArjunShankar
  • 23,020
  • 5
  • 61
  • 83
The Man
  • 1,462
  • 3
  • 23
  • 45

2 Answers2

3

Try this:

NSMutableArray *updated = [[NSMutableArray alloc] init];
for (NSArray *a in rootArray)
{
    if ([[a objectAtIndex:2] isEqualToString:@"hello"])
        [updated addObject:a];
}

Now updated will contain the arrays in rootArray whose 3rd object is @"hello".

Don't forget to release it after use (if you don't use ARC).

You can also use predicates for simple logic; see the NSPredicate class.

2

You can filter your array using NSPredicate, like this:

NSArray *data = [NSArray arrayWithObjects:
    [NSArray arrayWithObjects:@"One", @"Two", nil]
,   [NSArray arrayWithObjects:@"Three", @"Four", nil]
,   [NSArray arrayWithObjects:@"Nine", @"Two", nil]
,   nil];
NSPredicate *filter = [NSPredicate predicateWithBlock:^BOOL(id array, NSDictionary *bindings) {
    // This is the place where the condition is specified.
    // You can perform arbitrary testing on your nested arrays
    // to determine their eligibility:
    return [[array objectAtIndex:1] isEqual:@"Two"];
}];
NSArray *res = [data filteredArrayUsingPredicate:filter];
NSLog(@"%lu", res.count); 
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523