convert array format according to array character - ios

I have array in this format
rows = [[NSArray alloc] initWithObjects:#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica",
#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug" #"drums",
#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral",
#"Mark", #"Madeline",
#"Nemesis", #"nemo", #"name",
#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario",
#"Zeus", #"Zebra", #"zed", nil];
But i need this in to following format
rows = #[#[#"adam", #"alfred", #"ain", #"abdul", #"anastazja", #"angelica"],
#[#"dennis" , #"deamon", #"destiny", #"dragon", #"dry", #"debug", #"drums"],
#[#"Fredric", #"France", #"friends", #"family", #"fatish", #"funeral"],
#[#"Mark", #"Madeline"],
#[#"Nemesis", #"nemo", #"name"],
#[#"Obama", #"Oprah", #"Omen", #"OMG OMG OMG", #"O-Zone", #"Ontario"],
#[#"Zeus", #"Zebra", #"zed"]];
Means that same starting character in to different dictionary

The easiest approach.
NSArray *rows = ...;
NSMutableDictionary *map = [NSMutableDictionary dictionary];
for (NSString *value in rows) {
NSString *firstLetter = [value substringToIndex:1];
if (!map[firstLetter]) {
map[firstLetter] = #[];
}
NSMutableArray *values = [map[firstLetter] mutableCopy];
[values addObject:value];
map[firstLetter] = values;
}
NSArray *finalRows = [map allValues];
Note that finalRows is not sorted.

If you want to sort your array by it's first letter, you can try this :
NSMutableArray *outputArray = [NSMutableArray new];
NSString *lastFirstLetter = nil;
for(NSString *value in rows) {
NSString *firstLetter = [[value substringToIndex:1] lowerString];
if(![lastFirstLetter isEqualToString:firstLetter]) {
lastFirstLetter = firstLetter;
[outputArray addObject:[NSMutableArray new]];
}
[[outputArray lastObject] addObject:value];
}
The idea is to iterate your input array and if the first letter of your word is different than the precedent, create a new array.

Related

how to get nsDictionary element by using for-in

NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
for (NSDictionary* tmp in myDict) {
NSLog(#"%#",tmp);
}
resut:
my tmpis NSString
I want to get a dictionary with key= one , value = 1
for in for NSDictionary will iterate the keys.
for (NSString * key in myDict) {
NSLog(#"%#",key);
NSString * value = [myDict objectForKey:key];
}
If you want to get a dictionary. You have to create a dictionary from these values
for (NSString * key in myDict) {
NSLog(#"%#",key);
NSString * value = [myDict objectForKey:key];
NSDictionary * dict = #{key:value};
}
Or you should init like this:
NSArray *arrDict = #[{#{"one":#"1"},#{#"two":#"2"}];
for (NSDictionary* tmp in arrDict) {
NSLog(#"%#",tmp);
}
You can get all keys from your dic then add the key and value to your new dic like this:
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
NSArray *keys = [myDict allKeys];
for (NSString *key in keys) {
NSDictionary *yourDic = #{key: [myDict valueForKey:key]};
NSLog(#"%#", yourDic);
}
You didn't create it that way. If you wanted to have a NSDictionary inside another NSDictionary you should write something like this :
NSDictionary *myDict = #{
#"firstDict" : #{
#"one":#"1"
},
#"secondDict": #{
#"two":#"2"
}
};
Above code will create a NSDictionary with two dictionaries at keys #firstDict and #secondDict.
Also, bear in mind, that because dictionaries are key-value pairs, using a for-in loop, actually loops through the keys in that dictionary. So your code is equivalent to:
for(NSString *key in dict.allKeys) { ... }
I got the solution
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
NSMutableArray *arrayObject = [[NSMutableArray alloc]init];
NSMutableArray *arrayKey = [[NSMutableArray alloc]init];
NSMutableArray *arrayObjectKey = [[NSMutableArray alloc]init];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (NSString *stringValue in myDict.allValues)
{
[arrayObject addObject:stringValue];
}
for (NSString *stringKey in myDict.allKeys)
{
[arrayKey addObject:stringKey];
}
for(int i = 0;i<[arrayKey count];i++)
{
dict = [[NSMutableDictionary alloc]initWithObjectsAndKeys:[NSString stringWithFormat:#"%#",[arrayKey objectAtIndex:i]],#"key",nil];
[dict setObject:[NSString stringWithFormat:#"%#",[arrayObject objectAtIndex:i]] forKey:#"value"];
[arrayObjectKey addObject:dict];
}
NSLog(#"The arrayObjectKey is - %#",arrayObjectKey);
The Output is
The arrayObjectKey is -
(
{
key = one;
value = 1;
},
{
key = two;
value = 2;
}
)
Create the dictionary:
NSDictionary *myDict = [NSDictionary dictionaryWithObjectsAndKeys:#"1",#"One",#"2","Two",nil];
Get a value out using:(this example tmp will be 1)
NSString *tmp = [myDict objectForKey:#"One"];
Display the output in console:
NSLog(#"%#",tmp);
To display the whole NSDictionary
NSLog (#"contents of myDict: %#",myDict);
What you are doing is creating a dictionary with key-value pairs. I think what you want to do is have an array with dictionaries.
NSArray *myArray = #[#{#"one":#"1"}, #{#"two":#"2"}];
for (NSDictionary* tmp in myArray) {
NSLog(#"%#",tmp);
}
However I don't see a point in doing this. What you could do is:
NSDictionary *myDict = #{#"one":#"1",#"two":#"2"};
for (NSString* key in [myDict allKeys]) {
NSLog(#"%# = %#", key, myDict[key]);
}

NSMutableDictionary setValue:/forKey:? [duplicate]

This question already has answers here:
Sort array into dictionary
(5 answers)
Closed 7 years ago.
I have a NSMutableArray named animals. I need to create an NSMutableDictionary such that all names in the animals array have Keys that start with a specific first letter = Values.
This is animals array :
NSMutableArray *animals = [NSMutableArray arrayWithObjects:#"Bear", #"Black Swan", #"Buffalo", #"Camel", #"Cockatoo", #"Dog", #"Donkey", #"Emu", #"Giraffe", #"Greater Rhea", #"Hippopotamus", #"Horse", #"Koala", #"Lion", #"Llama", #"Manatus", #"Meerkat", #"Panda", #"Peacock", #"Pig", #"Platypus", #"Polar Bear", #"Rhinoceros", #"Seagull", #"Tasmania Devil", #"Whale", #"Whale Shark", #"Wombat", nil];
this is my code to set it into a MutableDictionary :
for(NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
NSArray *newArr = [NSArray arrayWithObject:str];
[myMutableDictionary setValue:newArr forKey:firstLetter];
}
The problem is that for each key only one value is set, but i need all the objects have a first letter with the same value. E.g. value='b' -> #"Bear", #"Black Swan", #"Buffalo".
Try
for (NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
if(!myMutableDictionary[firstLetter])
{
myMutableDictionary[firstLetter] = [NSMutableArray new];
}
NSMutableArray *arr = myMutableDictionary[firstLetter];
[arr addObject:str];
}
Here are the code that satisfied your requirement.
Step 1 : Allocate NSMutableDictionary.
Step 2 : While parsing NSArray, check initial is there key available in dictionary or what. if available then that array from same key and add new element in array and update same key in dictionary. if not available then create new key in dictionary. here is code.
NSMutableDictionary* dictTemp = [[NSMutableDictionary alloc]init];
for (NSString *str in animals) {
NSString *firstLetter = [str substringToIndex:1];
if([[dictTemp allKeys] containsObject:firstLetter]){
NSMutableArray* arrayInner = [NSMutableArray arrayWithArray:[dictTemp valueForKey:firstLetter]];
[arrayInner addObject:str];
[dictTemp setValue:arrayInner forKey:firstLetter];
}
else{
NSMutableArray* arrayInner = [[NSMutableArray alloc] init];
[arrayInner addObject:str];
[dictTemp setValue:arrayInner forKey:firstLetter];
}
}
NSLog(#"Output : %#",dictTemp);

Put multiple arrays in Dictionary

I am parsing a CSV file multiple times with for loop, here I need to store these arrays one by one dictionary. There are very less questions in stack about adding NSArray to NSDictionary. I am parsing CSV with below code but I strucked at storing in NSDictionary, The program is terminating and showing warning at assigning string to dictionary
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serail No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjects: keysArray forKeys: string];
}
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSString *key = [NSString stringWithFormat:#"serial%d",i];
[dict setObject:keysArray forKey:key];
}
To get back data from dictionary,
NSArray *array = [dict valueForKey:#"serial24"];//to get array 24.
If I understand you correctly, you want to add the arrays to a dictionary, with the key being the string value of integer i ? What you need to do is allocate the dictionary outside your loop -
NSMutableDictionary *dict=[NSMutableDictionary new];
for (i=0; i<=57; i++) {
NSString *keysString = [csvArray objectAtIndex:i];
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
NSLog(#"Serial No %d %#",i,keysArray);
NSString *string = [NSString stringWithFormat:#"%d", i];
dict[string]=keysArray;
}
I am not sure why you would want to do this, because this is basically an array. You could simply do -
NSMutableArray *outputArray=[NSMutableArray new];
for (NSString *keysString in csvArray) {
NSArray *keysArray = [keysString componentsSeparatedByString:#","];
[outputArray addObject:keysArray];
}

NSString remove duplicated substrings

How can I remove duplicated substings from string? For ex. I have: aaa,bbb,ttt,bbb,rrr.
And in result I want to have aaa,bbb,ttt,rrr (deleted duplicated bbb). I hope for your help. Thanks.
You can do it like this:
NSMutableSet *seen = [NSMutableSet set];
NSMutableString *buf = [NSMutableString string];
for (NSString *s in [str componentsSeparatedByString:#","]) {
if (![seen containsObject:s]) {
[seen add:s];
[buf appendFormat:#",%#", s];
}
}
NSString *res = [buf length] ? [buf substringFromIndex:1] : #"";
Do it in three steps
1) NSArray *items = [theString componentsSeparatedByString:#","];
2) remove duplicate element from array
NSArray* array = [NSArray arrayWithObjects:#"test1", #"test2", #"test1", #"test2",#"test4", nil];
NSArray* filteredArray = [[NSArray alloc] init];
NSSet *set= [NSOrderedSet orderedSetWithArray:array];
filteredArray = [set allObjects];
3) Concate String from array
NSString *myString = [myArray componentsJoinedByString:#","];
You can use NSMutableDictionary;
In dictionary there are two elements;
1. Key
2. Value
Just set Keys as your array elements;
Special point is that 'Key' can't be duplicate;
Now just get array of Keys by using [dictionary allKeys];
Now, at this stage you have unique values in new array;

How to separate contents from NSArray into two new one in Objective C?

any one here have an idea how I could separate this array in to 2??
2013-08-25 02:47:47.052 yahoo[11357:c07] (
"",
"1377253260000.33300.0",
"1377253440000.33280.0",
"1377254100000.33280.0",
"1377255600000.33220.0",
"1377257400000.33220.0",
"1377261660000.33200.0",
"1377264000000.33200.0",
"1377264060000.33200.0",
"1377267780000.33200.0",
"1377271260000.33200.0",
"1377273120000.33200.0",
"1377273180000.33200.0",
"1377273240000.33240.0",
""
)
The first NSArray would be with the long numbers and the second with the smaller one including the ".".
So something like: array1 with 1377253260000 and array2 with 33300.0 and so on.
There are tons of different ways of doing this. For example, you could do something as simple as find the first period, and add the string up to that period in the first array and everything after in the next array:
NSMutableArray *smallerNumbers = [NSMutableArray array];
NSMutableArray *longNumbers = [NSMutableArray array];
for (NSString *string in array) {
NSRange range = [string rangeOfString:#"."];
if (range.location != NSNotFound) {
[longNumbers addObject:[string substringToIndex:range.location - 1]];
[smallerNumbers addObject:[string substringFromIndex:range.location + 1]];
} else {
[longNumbers addObject:#""]; // or you could insert [NSNull null] or whatever
[smallerNumbers addObject:#""];
}
}
Another way..
NSArray *objects = #[
#"",
#"1377253260000.33300.0",
#"1377253440000.33280.0",
#"1377254100000.33280.0",
#"1377255600000.33220.0",
#"1377257400000.33220.0",
#"1377261660000.33200.0",
#"1377264000000.33200.0",
#"1377264060000.33200.0",
#"1377267780000.33200.0",
#"1377271260000.33200.0",
#"1377273120000.33200.0",
#"1377273180000.33200.0",
#"1377273240000.33240.0",
#""
];
NSMutableArray *firstParts = [[NSMutableArray alloc] initWithCapacity:objects.count];
NSMutableArray *secondParts = [[NSMutableArray alloc] initWithCapacity:objects.count];
for (NSString *object in objects)
{
NSArray *components = [object componentsSeparatedByString:#"."];
if (components.count > 0) {
[firstParts addObject:components[0]];
}
if (components.count > 1) {
[secondParts addObject:components[1]];
}
}
NSLog(#"firstParts = %#", firstParts);
NSLog(#"secondParts = %#", secondParts);

Resources