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?

7
  • btw this is unrelated to MySQL - it's a generic data structure question. And databases are also a data structure... :-) Commented Jul 3, 2012 at 20:27
  • I removed the MySQL and C tags, which are definitely unrelated. Commented Jul 3, 2012 at 20:28
  • @TheMan, read this question. I would even say its a possible duplicate. Commented Jul 3, 2012 at 20:30
  • Btw, the second object is not at index 2! Obviously, it's at index one. Commented Jul 3, 2012 at 20:32
  • that's why I wrote "the 3rd object" in my answer. Commented Jul 3, 2012 at 20:33

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Surely a predicate would be better here?
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); 

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.