Rajeev
Rajeev

Reputation: 99

Merge array1 and array 2 values into array3 objective c

I have a problem regrading merging of multiple array values into single array. Following are the arrays:

array1
(

{
    Id = 10166;
    Name = "Paul";
},
{
    Id = 10167;
    Name = "Dipleep";
},
{
    Id = 10168;
    Name = "John";

}
 )

array 2
(
{

    Country = USA;
},
{

    Country = India;
},
{

    Country = USA;

}
)

array3

(
{
    Id = 10166;
    Name = "Paul";
    Country = USA;
},
{
    Id = 10167;
    Name = "Dipleep";
    Country = India;
},
{
    Id = 10168;
    Name = "John";
    Country = USA;

}
)

I have no idea how to do but tried a bit like:

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

[newArr addObjectsFromArray:cartArray];
[newArr addObjectsFromArray:couponsArray];

But adding it wrongly. Could you please find me the solution for combining multiple array values into another array. TIA

Upvotes: 1

Views: 118

Answers (2)

Larme
Larme

Reputation: 26066

This is quite a simple task: You iterate, create a new dictionary combining the values from the object in array1 and in array2 at the same index.

NSMutableArray *array3 = [[NSMutableArray alloc] init];
for (NSUInteger i = 0; i < [array1 count]; i ++)
{
    NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
    [tempDict addEntriesFromDictionary:array1[i]];
    [tempDict addEntriesFromDictionary:array2[i]];
    [array3 addObject:tempDict];
}

As simple as it may be, there are still some issues that you could have and could cause a crash. You may not fall into these cases, but another user that have the same question could.

So now, what you need to think about:
• What if array1[n] keys has a common key with array2[n]? Because keys in dictionaries are unique. So the value will be replaced (check the doc of addEntriesFromDictionary:)
• What if [array1 count] is different from [array2 count]? Yeah the for loop may crash due to an out of bounds issue.
• Why is your data separated like this at the beginning? You are trying to "resynchronize" them, that's good, but are you sure that they are correctly synchronized? I mean, that array1[n] values really correspond to array2[n] and not array2[m] values? Especially if you are getting them asynchronously...

Upvotes: 1

Ketan Parmar
Ketan Parmar

Reputation: 27438

You can do like,

for (int i = 0; i < array1.count; i++) {


    NSString *idOfObj = [[array1 objectAtIndex:i] objectForKey:@"Id"];
    NSString *name = [[array1 objectAtIndex:i] objectForKey:@"Name"];
    NSString *country = [[array2 objectAtIndex:i] objectForKey:@"Country"];

    NSDictionary *dic = @{@"Id" :idOfObj,@"Name" : name,@"Country" : country};

    [array3 addObject:dic];
}

NSLog(@"result array : %@",array3);

Upvotes: 1

Related Questions