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

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

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

我有数百个这样的数组给我最佳解决方案。我不喜欢嵌套 ForLoops

1。我需要 Distinct Union the Array By 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。我必须在字典中设置对象 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;
    }