1
votes

I have 3 NSMutableArrays k,names,numbers

k array contains {a,b,c,d,e,.....}

names array contains {apple,bag,banana,car,cat,dall,elephant,.....}

numbers array contains {100,200,300,400,500,600,700,...}

All the 3 arrays are dynamic here.

I want to add names[],numbers[] to NSMutableDictionary with k[] as key array..

My output should be like this when i pint that dictionary

a

apple 100

b

bag 200

banana 300

c

car 400

cat 500

d

dall 600

e

elephant 700

Could somebody help me. thank you.

3
Are all the arrays of equal length? Is the names array already sorted?Cutetare

3 Answers

0
votes
NSMutableDictionary *result = [NSMutableDictionary new];
for(int i = 0; i<k.count; i++){
    unichar letter = [k objectAtIndex:i]; //I'm assuming you have chars in your k array,            
                                           // if not, you have to format it here
    NSString* name = [names objectAtIndex:i];
    if([[name characterAtIndex:0] isEqual:letter]){
        NSString *objectToInsert = [NSString stringWithFormat:@"%@: %@", @"name", [numbers objectAtIndex:i]];
        [result setObject:objectToInsert forKey:letter];
    }
}

You can probably optimize this more, but it should work ;)

0
votes

Try with following code

NSMutableDictionary *mydic = [[NSMutableDictionary alloc] init];

For(int k = 0; k < firstArray.count ; k++)
{
  NSPredicate *pred =[NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", [firstArray objectAtIndex:k]];
  NSArray *filteredArr = [MySecodArray filteredArrayUsingPredicate:pred];

  NSString *myString = @"";
  for (int t = 0 ; t < filteredArr.count ; t ++)
  {
    myString = [MyThirdArray objectAtIndex:[MySecodArray indexOfObject:[filteredArr  objectAtIndex:t]]];
    myString = [[filteredArr  objectAtIndex:t] stringByAppendingString:myString];
    [mydic setValue: myString forKey:[firstArray objectAtIndex:k]];

    myString = @"";   
  }
}
NSLog(@"%@", myDic);
0
votes

You can do like This,I am assuming nameArry and NumberArray count is same-->

try This code

NSSMutableDictionary *finalDictionary = [[NSSmutableDictionary alloc]init];
for(int i=0;i<k.count;i++)
{
   NSString *alphaBet = [k objectAtIndex:i];

   //initialize array here 

   NSMutableArray *insideDictArray = [[NSMutableArray alloc]init];

   for(int j=0;j<nameArray.count;j++)
   {
     NSString *name = [nameArray objectAtIndex:j];
     if([name hasPreffix:alphabet])
     {
       //get Number String

       NSString *numberForName = [numberArray objectAtIndex:j];

       //Now Concate Number and Name

       NSString *concateString = [name stringByAppendingFormat:@"
       %@",numberForName]; 

       //Put this in Array we just intialized outside of secondLoop

      [insideDictArray addObject:concateString];        
     }
   }
   //Now Add array to finalDictionary

   [finalDictionary addObject:insideDictArray forKey:alphabet];
}

OutPut Will Be like this i hope :

finalDictionary = 
{
a = [aple 100];
b = [bag 200,banana 300];
.
.
}