0

I have NSArray1 = (1, 5, 2) and NSArray2 = (1, 3, 5)

i want to array1 + array2 = (should return) = (2, 8, 7)

(in fact is it even possible to do this with NSArray)?

Heres a similar question Adding two arrays together (but this adds the values of the second array onto the end of the first array)

NSArray *a = [NSArray arrayWithObjects: @"1" ,@"2",@"3",nil];
NSArray *b = [NSArray arrayWithObjects: @"1" ,@"2",@"3",nil];
NSMutableArray *c = [[NSMutableArray alloc]init];
c = [a addObjectsFromArray:b];

// just a test code . . . .

1
  • If you really want to use code similar to what you've written in your sample, you would need to create a category on NSArray and implement the new array creation in a addObjectsFromArray method there. Commented Oct 1, 2012 at 12:22

1 Answer 1

1

If it's a C array, then just do

int newArray[3];
for (int i=0;i<3;i++)
    newArray[i] = array1[i]+array2[i];

But if it's a NSArray with NSNumbers (You can't have primitives in NSArray), then just do

NSMutableArray *newArray = [NSMutableArray array];
for (int i=0;i<[array1 count];i++)
    [newArray addObject:[NSNumber numberWithInt:[[array1 objectAtIndex:i] intValue]+[[array2 objectAtIndex:i] intValue]]];
    //If you're using Mountain Lion, then you can use the following 
    //[newArray addObject:@([array1[i] intValue]+[array2[i] intValue])];

Edit:

If you have more than 1 array, then

int numArrays = 3;
NSArray *arrayOfNum = //An array of arrays that contains all the numbers
NSMutableArray *newArray = [NSMutableArray array]
for (int i=0;i<[array1 count];i++)
{
    int total = 0;
    for (int x=0;x<numArrays;x++)
        total+=[arrayOfNum[x] intValue];
    [newArray addObject:@(total)];
}
Sign up to request clarification or add additional context in comments.

2 Comments

To clarify addObject places values at the end value of the array, which works but nonetheless if you have more then one array to add it does not work consider using replaceObjectAtIndex if adding more then 1 array or when iterating through multiple Arrays.
What...? If you have more than one array you can just do [newArray addObject:@([array1[i] intValue]+[array2[i] intValue]+[array3[i] intvalue]). Or if you have an unknown amount of arrays to add, you can create another loop, which I'll add some sample code to my question.

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.