Rebuild an NSArray by grouping objects that have matching id numbers?

前端 未结 5 1216
醉酒成梦
醉酒成梦 2020-11-29 06:38

I have an NSArray and each object in the array has a groupId and a name. Each object is unique but there are many with the same groupId. Is there a way i can tear the arra

5条回答
  •  有刺的猬
    2020-11-29 07:36

    The below code will Rebuild an NSArray by grouping objects w.r.t any matching keys in each dictionary in that array

    //only to a take unique keys. (key order should be maintained)
    NSMutableArray *aMutableArray = [[NSMutableArray alloc]init];
    
    NSMutableDictionary *dictFromArray = [NSMutableDictionary dictionary];
    
    for (NSDictionary *eachDict in arrOriginal) {
      //Collecting all unique key in order of initial array
      NSString *eachKey = [eachDict objectForKey:@"roomType"];
      if (![aMutableArray containsObject:eachKey]) {
       [aMutableArray addObject:eachKey];
      }
    
      NSMutableArray *tmp = [grouped objectForKey:key];
      tmp  = [dictFromArray objectForKey:eachKey];
    
     if (!tmp) {
        tmp = [NSMutableArray array];
        [dictFromArray setObject:tmp forKey:eachKey];
     }
    [tmp addObject:eachDict];
    
    }
    
    //NSLog(@"dictFromArray %@",dictFromArray);
    //NSLog(@"Unique Keys :: %@",aMutableArray);
    

    //Converting from dictionary to array again...

    self.finalArray = [[NSMutableArray alloc]init];
    for (NSString *uniqueKey in aMutableArray) {
       NSDictionary *aUniqueKeyDict = @{@"groupKey":uniqueKey,@"featureValues":[dictFromArray objectForKey:uniqueKey]};
       [self.finalArray addObject:aUniqueKeyDict];
    }
    

    Hope it may help..

提交回复
热议问题