Objective C: Create arrays from the first array based on a value

I have an array of comma separated strings like:

Steve Jobs,12,CA
Fake Name,21,CA
Test Name,22,CA
Bill Gates,44,WA
Bill Nye,21,OR

      

I have these values ​​in an NSScanner object so that I can loop through the values ​​and get each comma separated value using objectAtIndex.

So what I would like to do is group the elements of the array into new arrays based on value, in this case State. So from them I need to go through, check what state they are in, and insert them into a new array, one array for each state.

CA Array:
Steve Jobs,12,CA
Fake Name,21,CA
Test Name,22,CA

WA Array:
Bill Gates,44,WA

OR Array:
Bill Nye,21,OR

      

So in the end, I would have 3 new arrays, one for each state. Also, if there were additional states in the first array, they should create new arrays as well.

Any help would be appreciated!

+2


a source to share


3 answers


You can use NSMutableDictionary

of NSMutableArray

- if the detected state is not already in the dictionary, add a new array.

NSMutableArray* arr = [states objectForKey:state];
if (arr == nil) {
    arr = [NSMutableArray array];
    [states setObject:arr forKey:state];
}

      



You can then insert values ​​into the array, preferably as objects, although Dave DeLong is mentioned.

+2


a source


You don't have to support this data as CSV. It takes a world of pain if you ever need to manipulate that data programmatically (like what you are trying to do).



You can naively split this data into an array with NSArray * portions = [line componentsSeparatedByString:@","];

. Then create a custom object to hold each part (see this post for example ) and then you can manipulate those objects easily.

+1


a source


Naively: (assuming an array of strings called strings)

NSMutableDictionary *states = [NSMutableDictionary dictionary];
for (NSString *string in strings) {
  NSString *state = [[string componentsSeparatedByString:@", "] lastObject];  
  NSMutableArray *values = [states objectForKey:state];
  if (values == nil) {
     values = [NSMutableArray array];
     [states setObject:value forKey:state];
  }
  [values addObject:string];
}

      

A few things about this - firstly, I'm not on my computer, so there is a high chance of typos and things I missed. Second, you probably want to adapt string-separated components for better whitespace management.

0


a source







All Articles