NSMutableDictionary setValue:/forKey:? [duplicate] - ios

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);

Related

Create alphabetical NSDictionary from NSArray [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
Let's say I have an array that looks like this:
NSArray *array = #[#"Bear", #"Black Swan", #"Buffalo", #"Camel", #"Cockatoo", #"Dog", #"Donkey", #"Emu"]
How can I create following dictionary out of it?
NSDictionary *animals;
animals = #{#"B" : #[#"Bear", #"Black Swan", #"Buffalo"],
#"C" : #[#"Camel", #"Cockatoo"],
#"D" : #[#"Dog", #"Donkey"],
#"E" : #[#"Emu"]};
If I understand the question correctly you are trying to create a dictionary out of an array.
Try this:
NSArray *array = #[#"Bear", #"Black Swan", #"Buffalo", #"Camel", #"Cockatoo", #"Dog", #"Donkey", #"Emu"];
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
for (NSString *animal in array) {
NSString *firstLetter = [animal substringToIndex:1];
if (!dictionary[firstLetter]) {
dictionary[firstLetter] = [[NSMutableArray alloc] init];
}
[((NSMutableArray *)dictionary[firstLetter]) addObject:animal];
}
At the end the value of dictionary is:
dictionary = #{#"B" : #[#"Bear", #"Black Swan", #"Buffalo"],
#"C" : #[#"Camel", #"Cockatoo"],
#"D" : #[#"Dog", #"Donkey"],
#"E" : #[#"Emu"]};
I think you want to do this by :
NSMutableDictionary* animals =[NSMutableDictionary new];
NSArray* wAnimals =#[#"Whale", #"Whale Shark", #"Wombat"];
[animals setObject:wAnimals forKey:#"W"];
Please try this (Hope this will help you and i think you want like this)-
-(NSDictionary*)makeCustomDictionary:(NSString*)yourValue{
[array addObject:yourValue];
NSMutableArray *lettersKey = [NSMutableArray array];
NSMutableArray *values = [NSMutableArray array];
for (NSString *string in array) {
if (string.length > 0) {
NSString *letter = [string substringToIndex:1];
if (![lettersKey containsObject:letter]) {
[lettersKey addObject:letter];
NSString *stringToSearch = letter;
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#",stringToSearch]; // if you need case sensitive search avoid '[c]' in the predicate
NSArray *results = [array filteredArrayUsingPredicate:predicate];
[values addObject:results];
}
}
}
return [NSDictionary dictionaryWithObjects:values forKeys:lettersKey];
}
- (IBAction)addNewValue:(id)sender {
NSDictionary *tempDic=[self makeCustomDictionary:txt.text];
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:tempDic
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string
error:&error];
if (! jsonData) {
NSLog(#"Got an error: %#", error);
} else {
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"dictionary in json form - %# \n\n or dictionary simple- %#",jsonString,tempDic);
}
}
here array is global NSMutableArray initialize in viewDidLoad().
Output-
dictionary in json form -
{
"D" : ["Dog","Donkey"],
"B" : ["Bear","Black Swan","Buffalo"],
"G" : ["Giraffe"],
"E" : ["Emu"],
"C" : ["Camel","Cockatoo"]
}
or dictionary simple- {
B = (
Bear,
"Black Swan",
Buffalo
);
C = (
Camel,
Cockatoo
);
D = (
Dog,
Donkey
);
E = (
Emu
);
G = (
Giraffe
);
}

How to get first string of NSArray

Pretty straightforward question:
I have an array like so:
#[#"John Doe", #"Mister Appleseed", #"Steve"];
if it has two (or more) words, I want to delete them all but the first, so the output array should looke something like this:
#[#"John", #"Mister", #"Steve"];
How do I do this?
NSArray * arr = #[#"John Doe", #"Mister Appleseed", #"Steve"];
NSMutableArray * tmp = [NSMutableArray array];
for (NSString * s in arr)
{
NSArray * cmpnts = [s componentsSeparatedByString:#" "];
[tmp addObject:cmpnts[0]];
}
arr = tmp;
Check the following code:
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
NSArray *sourceArray = #[#"John Doe", #"Mister Appleseed", #"Steve"];
for(NSString *str in sourceArray){
[finalArray addObject:[str componentsSepratedByString:#" "] objectAtIndex:0]];
}
You iterate over the array of names, split each at spaces (" "), and then grab the first object: the first name.
NSArray *nameArray = #[#"Name", #"Name Two"]; // original array
NSMutable *modifiedNameArray = [NSMutableArray new]; // new mutable array to add new names
for (NSString *fullName in nameArray) { // for loop
NSString *firstName = [[fullName componentsSeparatedByString:#" "] objectAtIndex:0]; // extract first name
[modifiedNameArray addObject:firstName]; // add first name to mutable array
}
You have to have two arrays, because you cannot mutate an array while it is being used in a loop (even if it's an NSMutableArray).

convert array format according to array character

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.

Merge arrays with its count in Objective C

I have an array like this
A = [#"aa",#"cc",#"bb",#"bb",#"cc",#"aa",#"cc"]
I need to convert it to
A = [#"x2 aa",#"x2 bb",#"x3 cc"]
Count the similar elements and create a new string, add it to new array. As shown here:
NSArray *aArray = #[#"aa", #"cc", #"bb", #"bb", #"cc", #"aa", #"cc"];
NSCountedSet *set = [NSCountedSet setWithArray:aArray];
NSMutableArray *countedArray = [NSMutableArray new];
for (NSString *str in set) {
[countedArray addObject:[NSString stringWithFormat:#"x%ld %#",[set countForObject:str], str]];
}
NSLog(#"%#",countedArray);
Output:
(
"x2 bb",
"x2 aa",
"x3 cc" )

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;

Resources