1

Is there a one-liner to do the following

NSMutableArray *allpoints = [[NSMutableArray alloc] init];
for (NSMutableArray *arr in self.points)
     [allpoints addObjectsFromArray:arr];

I have an array of arrays (self.points) and I am joining all of the objects in the subarrays into a single array.

4 Answers 4

7
NSArray *array1 = @[ @"a", @"b", @"c" ];
NSArray *array2 = @[ @"d", @"e", @"f" ];
NSArray *array3 = @[ array1, array2 ];
NSArray * flattenedArray = [array3 valueForKeyPath:@"@unionOfArrays.self"];
NSLog(@"flattenedArray: %@", flattenedArray);

Output:

flattenedArray: ( a, b, c, d, e, f )

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

1 Comment

This is definitely the correct answer; it'd be allpoints = [self.points valueForKeyPath:@"@unionOfArrays.self"] to apply directly to the question (and add a mutableCopy if you really want that characteristic on allPoints).
1

There is not a way to add all objects in an array of arrays (e.g., every NSMutableArray in self.points to another array without iterating through.

However, you could add a category to NSArray to do exactly what you're doing now, and then call it with one line later.

Comments

0

If you are initializing the array and adding objects at the same time then there is an initializer for that.

NSMutableArray *allpoints = [[NSMutableArray alloc] initWithArray:self.points];

If you already have the mutable array defined and you want to just append objects to the end then you can use the following.

[allpoints addObjectsFromArray:self.points];

2 Comments

self.points is an array containing more arrays—OP wants to add the elements from these arrays, not the arrays themselves.
Ahh, well in that case then yeah he will have to iterate through them. I mean if it's something he's doing alot then maybe he can create a category on NSMutableArray but for most applications that would probably be a little overkill.
0

I don't think there is a way to do this.

NSMutableArray *allpoints = [[NSMutableArray alloc] initWithArray:self.points]

would give you an array of the arrays, but there is no single line solution. I'd suggest writing a category that will do this for you so you can easily reuse it.

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.