Abhinandan Pratap
Abhinandan Pratap

Reputation: 2148

Split an NSArray into a fixed size and the rest

I have an NSArray in my project which has nearly 12 elements. I want to split this array into 2 arrays. I want the first 3 elements in the first array and the rest of the elements in the second NSArray.

Upvotes: 0

Views: 154

Answers (2)

Alex Chase
Alex Chase

Reputation: 1091

As a category of NSArray :

@implementation NSArray (NSArray_Slicing)

- (NSArray *)subarraysFromIndex:(int)index {
    return @[[self sliceToIndex:index], [self sliceFromIndex:index]];
}


- (NSArray *)sliceFromIndex:(int)index {
    NSMutableArray*mutArray = [self mutableCopy];
    NSRange range = NSMakeRange(index, self.count - index);
    return [mutArray subarrayWithRange:range];
}


- (NSArray *)sliceToIndex:(int)index {
    NSMutableArray*mutArray = [self mutableCopy];
    NSRange range = NSMakeRange(0, index);
    return [mutArray subarrayWithRange:range];
}

@end

And then to call it:

NSArray *array = @[@1, @2, @3, @4, @5, @6, @7, @8, @9, @10, @11, @12];
NSLog(@"First three: %@", [array sliceToIndex:3]);
NSLog(@"Remaining:   %@", [array sliceFromIndex:3]);
NSLog(@"Sliced:      %@", [array subarraysFromIndex:3]);
NSLog(@"Original:    %@", array);

Upvotes: 0

glyvox
glyvox

Reputation: 58069

Based on the answer of Alex Reynolds:

You should make a range that has the length of 3 and make the first half of the array with it, then modify its location and length and create the second half of the array.

NSArray *firstThreeArray;
NSArray *otherArray;
NSRange threeRange;

threeRange.location = 0;
threeRange.length = 3;

firstThreeArray = [wholeArray subarrayWithRange:threeRange];

threeRange.location = threeRange.length;
threeRange.length = [wholeArray count] - threeRange.length;

otherArray = [wholeArray subarrayWithRange:threeRange];

Upvotes: 1

Related Questions