繁体   English   中英

将NSArray的NSArray中的objectAtIndex值求和或将NSDictionary中的键的现有值与值相加

[英]Sum objectAtIndex values in NSArray of NSArray OR Add value with existing value for key in NSDictionary

我需要的任何一种解决方案。 建议我最好的答案。

我有数百个这样的阵列,可以为我提供最佳解决方案。 我不喜欢Nested ForLoops

1 我需要通过ObjectAtIndex:0来区分数组并在ObjectAtIndex:1中求和它们的值。

A-> [[1,“ 100.0”],[2,“ 100.0”],[2,“ 100.0”],[3,“ 100.0”],[4,“ 100.0”],[3,“ 100.0 “],[4,” 100.0" ]]

B-> [[1,250],[2,250],[1,250],[3,“ 200.2”],[1,“ 200.2”],[4,“ 200.2”],[1,“ 200.2”],[ 4, “200.2”]]

我需要这样的A--> [[1,"100.0"],[2,"200.0"],[3,"200.0"],[4,"200.0"]]

2。我必须在Dictionary中设置Object A和B数组。 但是如果关键字存在于字典中,则将该值与现有值相加。

{

 A =     {
    1 = 100;
    2 = 100;
    3 = 100;
    4 = 100;
};

 B =     {
    1 = 250;
    2 = 250;
    3 = "200.2";
    4 = "200.2";
};

}

喜欢

NSArray* uniqueValues = [data valueForKeyPath:[NSString stringWithFormat:@"@distinctUnionOfObjects.%@", @"self"]];
NSArray* A = @[@[@1, @100.0],@[@2, @100.0],@[@3, @100.0],@[@1, @100.0],@[@1, @100.0]];

NSMutableDictionary* sum = [NSMutableDictionary new];
for (NSArray* item in A)
{
    id key = item[0];
    if (sum[key] == nil)
    {
        sum[key] = item[1];
    }
    else
    {
        sum[key] = @([sum[key] floatValue] + [item[1] floatValue]);
    }
}

NSLog(@"%@", sum.description);

输出:

3 = 100;
1 = 300;
2 = 100;

基于KVC集合运算符的替代解决方案。

    NSArray* arrayOFArray = @[@[@1, @100.0],@[@2, @100.0],@[@3, @100.0],@[@1, @100.0],@[@1, @100.0]];

    NSMutableDictionary* sumDic = [NSMutableDictionary new];
    NSInteger index = 0; // By changing index position. You get unique sum either way.
    for (NSArray* item in arrayOFArray)
    {
       id key = item[index];
        if (key && sumDic[key] == nil) {

            NSArray *keyArray = [self findSameValueKey:arrayOFArray WithKey:key withIndex:index];
            NSArray *unionArray = [keyArray valueForKeyPath: @"@unionOfArrays.self"];
            NSNumber *sum = [unionArray valueForKeyPath:@"@sum.floatValue"];
            sumDic[key] = [NSNumber numberWithInt:[sum floatValue] - ([keyArray count]* [key floatValue])];
        }
    }

    NSLog(@"%@", sumDic.description);


    // Helps to find same value key.
    -(NSArray*)findSameValueKey:(NSArray*)dateArray WithKey:(NSString*)key withIndex:(NSInteger)index {
        NSPredicate *predicate = [NSPredicate predicateWithBlock:^BOOL(NSArray *resultsArray, NSDictionary *bind){
            if ([resultsArray[index] isEqual:key]) {
                return true;
            }
            return false;
        }];

        // Apply the predicate block .
        NSArray *sameValueKeys = [dateArray filteredArrayUsingPredicate:predicate];
        return sameValueKeys;
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM