iOS开发把数组按照条件分组

//把_dataArray中的数据按照时间分组(同一天的一组)

-(void)category

{

    //分好组的数组

    _titleArray=[NSMutableArray array];

    //遍历时,时间相同的装在同一个数组中,先取_dataArray[0]分一组

    NSMutableArray *currentArr=[NSMutableArray array];

    [currentArr addObject:_dataArray[0]];

    [_titleArray addObject:currentArr];

    

    if(_dataArray.count>1)

    {


        for (int i=1;i<_dataArray.count;i++)

        {

   //取上一组元素并获取上一组元素的比较日期

            NSMutableArray *preArr=[_titleArray objectAtIndex:_titleArray.count-1];

            

            NSString *pretime=[[preArr objectAtIndex:0] objectForKey:@"birthTime"];

            NSString *premonth=[[[[pretime componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:1];

            NSString *preday=[[[[pretime componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:2];

           NSString *preStr=[premonth stringByAppendingString:preday];

            //取当前遍历的字典中的日期

            NSDictionary *currentDict=[_dataArray objectAtIndex:i];

            NSString *time=[currentDict objectForKey:@"birthTime"];

            NSString *month=[[[[time componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:1];

            NSString *day=[[[[time componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:2];

            NSString *currentStr=[month stringByAppendingString:day];

            //如果遍历当前字典的日期和上一组元素中日期相同则把当前字典分类到上一组元素中

            if([currentStr isEqualToString:preStr])

            {

                [currentArr addObject:currentDict];

            }

    //如果当前字典的日期和上一组元素日期不同,则重新开新的一组,把这组放入到分类数组中

            else

            {

                currentArr=[NSMutableArray array];

                [currentArr addObject:currentDict];

                [_titleArray addObject:currentArr];

            

            }

            

        

        }

    

    }


}

调用上面那个方法后,_dataArray里面的数据会按照日期分成各组元素数组,存入_titleArray中。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值