0

I have two 2D arrays like

Array1 = [(1, 2), (3, 4), (5, 6)]

Array2 = [(x, y), (x, y), (x, y)]

I want to form a dictionary like "coordinates" = [{"x":"1", "y":"2"}, {"x":"3", "y":"4"},{"x":"5", "y":"6"}]

How do i do it?

2
  • Second array always have just x and y? Commented Sep 3, 2016 at 7:15
  • Yes! Only x and y Commented Sep 3, 2016 at 7:17

2 Answers 2

1

As you mention in comment second array always have x and y then there is no need to loop through that array, You need just iterate first array like this.

NSMutableArray *dicArray = [[NSMutableArray alloc] init];
for (NSArray *subArray in array1) {
    NSDictionary *dic = @{ @"x": [subArray firstObject], @"y": [subArray lastObject] };
    [dicArray addObject:dic];
}
NSLog(@"%@",dicArray);
Sign up to request clarification or add additional context in comments.

Comments

0

Another Alternative:

NSMutableArray *finalArray = [[NSMutableArray alloc] init];

for (NSArray* arr1 in Array1) {
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    for (NSArray* arr2 in Array2) {
        [dict setValue:arr1.firstObject forKey:arr2.firstObject];
        [dict setValue:arr1.lastObject forKey:arr2.lastObject];
    }
    [finalArray addObject:dict];
}

NSLog(@"%@", finalArray);

Comments

Your Answer

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