swift - 如果一个键在数组中重复,我想添加该键的值

标签 swift nsarray

如果一个键在数组中重复,我想合并该键的值。例如,我有以下数组。

var arrays = [
    ["Product":"Item0", "Price":"15"],
    ["Product":"Item1", "Price":"53"],
    ["Product":"Item2", "Price":"12"],
    ["Product":"Item1", "Price":"83"],
    ["Product":"Item0", "Price":"10"],
    ["Product":"Item3", "Price":"88"],
    ["Product":"Item0", "Price":"44"]
]

我想像这样改变这个数组。

[
    ["Product": "item0", "Price": "69"],
    ["Product": "item1", "Price": "136"],
    ["Product": "item2", "Price": "12"],
    ["Product": "item3", "Price": "88"]
]

我该怎么办?

这是我写的代码。但是,如果重复了两个以上的键,则不会显示确切的值。你能在这里稍微修一下还是给我一个新的方法?

var arrays= [
    ["Product":"Item0", "Price":"15"],
    ["Product":"Item1", "Price":"53"],
    ["Product":"Item2", "Price":"12"],
    ["Product":"Item1", "Price":"83"],
    ["Product":"Item0", "Price":"10"],
    ["Product":"Item3", "Price":"88"],
    ["Product":"Item0", "Price":"44"]
]

var filteredArrays = [[String:String]]()
var sum : Int = 0

for i in 0..<arrayOfDicts.count {

    let Product1 = arrayOfDicts[i]["Product"]

    if(i == 0){
        filteredArrays.append(arrayOfDicts[i])
    } else {

        var flag = false
        for j in 0..<filteredArrays.count {

            let Product2:String = filteredArrays[j]["Product"]!

            if Product1 == Product2 {

                sum += (Int(arrayOfDicts[i]["Price"]!)! + Int(arrayOfDicts[j]["Price"]!)!)

                filteredArrays[j] = ["Product":"\(arrayOfDicts[i]["Product"]!)", "Price":"\(sum)"]

                sum = 0
                flag = true
            }
        }

        if !flag {
            filteredArrays.append(arrayOfDicts[i])
        }
    }

}

谢谢

最佳答案

  1. 遍历您的产品
  2. 检查“Product”是否包含有效字符串
  3. 将价格提取为 Int(如果需要,也可以是 float)。默认为零以避免错误的总和。
  4. 创建一个以产品名称为键的字典,并用相同的键对值求和
  5. 字典转数组

    var result = [String : Int]()
    
    for product in arrays {
    
        if let productKey = product["Product"] {
             let value = Int(product["Price"] ?? "0")
             if result[productKey] == nil, let value = value {
                result[productKey] = value
             } else if let value = value {
                result[productKey]! += value
             }
        }
    }
    
    let newArray = result.map {["Product":$0, "Price": $1]}
    

关于swift - 如果一个键在数组中重复,我想添加该键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47017123/

相关文章:

macos - 将数据从 ViewController 传递到 TabViewController

swift - 有没有办法让函数接受任何具有 rawValue 字符串的枚举类型?

ios - 移动时保持 UICollectionView 中自定义单元格的大小

ios - 函数返回一个空数组而不是填充它

swift - 如何在 Swift 中获取值类型的引用?

iphone - 语义问题 : Incompatible pointer to integer conversion sending 'NSUInteger *' (aka 'unsigned int *' ) to parameter of type 'NSUInteger'

iphone - 在 iPhone 上使用 JSON 框架 - 帮助!

ios - 从 NSArray 中提取数据

arrays - 创建一个空的 NSArray

ios - 背景透明色