If a key is duplicated in an array,I want to add the values of that key

我是研究僧i 提交于 2019-12-24 12:15:25

问题


If a key is duplicated in an array, I want to combine the values of that key. For example, I have the following array.

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"]
]

And I want to change this array like this.

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

What should I do?

This is the code I wrote. However, if more than two keys are duplicated, the exact value is not displayed. Could you fix a little here or give me a new way at all?

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])
        }
    }

}

Thank you


回答1:


  1. Iterate through your products
  2. Check if "Product" contains valid string
  3. Extract price as Int (or float if needed). Default as zero to avoid wrong sum.
  4. Create a dictionary with product name as key and sum the values with same key
  5. Convert dictionary to array

    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]}
    



回答2:


Just for fun, not for the faint-hearted, using Swift 4 new method reduce(into:) and Dictionary Key-based subscript with default value:

let result = arrays.reduce(into: [String : Int]()) {
    $0[$1["Product"] ?? "", default: 0] += Int($1["Price"] ?? "") ?? 0 }
    .map { ["Product": $0, "Price": $1] }

print(result)

"[["Product": "Item0", "Price": 69], ["Product": "Item2", "Price": 12], ["Product": "Item1", "Price": 136], ["Product": "Item3", "Price": 88]]\n"



来源:https://stackoverflow.com/questions/47017123/if-a-key-is-duplicated-in-an-array-i-want-to-add-the-values-of-that-key

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!