Okay - let me know if this is clear.
// Setup the inital array
NSArray *array = [[NSArray alloc] initWithObjects:@"Anchorage, AK",
@"Juneau, AK",
@"Los Angeles, CA",
@"Minneapolis, MS",
@"Seatac, WA",
@"Seattle, WA", nil];
// Create our array of arrays
NSMutableArray *newArray2 = [[NSMutableArray alloc] init];
// Loop through all of the cities using a for loop
for (NSString *city in array) {
// Keep track of if we need to creat a new array or not
bool foundCity = NO;
// This gets the state, by getting the substring of the last two letters
NSString *state = [city substringFromIndex:[city length] -2];
// Now loop though our array of arrays tosee if we already have this state
for (NSMutableArray *subArray in newArray2) {
//Only check the first value, since all the values will be the same state
NSString *arrayCity = (NSString *)subArray[0];
NSString *arrayState = [arrayCity substringFromIndex:[arrayCity length] -2];
if ([state isEqualToString:arrayState])
{
// Check if the states match... if they do, then add it to this array
foundCity = YES;
[subArray addObject:city];
// No need to continue the for loop, so break stops looking though the arrays.
break;
}
}
// WE did not find the state in the newArray2, so create a new one
if (foundCity == NO)
{
NSMutableArray *newCityArray = [[NSMutableArray alloc] initWithObjects:city, nil];
[newArray2 addObject:newCityArray];
}
}
//Print the results
NSLog(@"%@", newArray2);
My output
2014-01-20 20:28:04.787 TemperatureConverter[91245:a0b] (
(
"Anchorage, AK",
"Juneau, AK"
),
(
"Los Angeles, CA"
),
(
"Minneapolis, MS"
),
(
"Seatac, WA",
"Seattle, WA"
)
)