代码之家  ›  专栏  ›  技术社区  ›  Bhavin Bhadani

字典数组:如果在单个字典中发现相同,则添加值

  •  0
  • Bhavin Bhadani  · 技术社区  · 7 年前

    我有一系列这样的结构

    [["grocery_section": "other", "partial_quantity": "0", "name": "Ground turmeric", "unit": "teaspoons", "whole_quantity": "1"],
    ["grocery_section": "other", "partial_quantity": "", "name": "I", "unit": "cups", "whole_quantity": "1"],
    ["grocery_section": "other", "partial_quantity": "", "name": "I", "unit": "cups", "whole_quantity": "2"]]
    

    现在,我想从该部分中具有相同键值对的配料中找到相同的条目,如果找到,我想在其中添加数量,并制作一种配料。您可以检查上面的数组,其中节名为“OTHER”,并检查其中的成分。我想把这两种相同的成分合并成一种,数量为1+1=2。所以,最终的结果应该是

    [["grocery_section": "other", "partial_quantity": "0", "name": "Ground turmeric", "unit": "teaspoons", "whole_quantity": "1"],
    ["grocery_section": "other", "partial_quantity": "", "name": "I", "unit": "cups", "whole_quantity": "3"]]
    

    My Code

        guard let first = ingredients.first else {
            return [] // Empty array
        }
    
        var uniqueIngredients: [[String:String]] = [first] // Keep first element
    
        for elem in ingredients.dropFirst() {
            let equality = ingredients.compactMap { $0["name"] == elem["name"] }.count
            if equality > 1 {
                // SAME NAME FOR 2 INGREDIENT FOUND
                // COMBINE BOTH OBJECT
            } else {
                // NEW NAME
                // ADD NEW OBJECT
            }
       }
    
    1 回复  |  直到 7 年前
        1
  •  2
  •   vadian    7 年前
    • 按将数组分组到字典 name
    • result
    • 列举字典。如果列表中有多个项目 value 汇总数量,只追加一项

    名称 whole_quantity 存在于所有记录和密钥的值中 全量 可以转换为 Int

    let array = [["grocery_section": "other", "partial_quantity": "0", "name": "Ground turmeric", "unit": "teaspoons", "whole_quantity": "1"],
                 ["grocery_section": "other", "partial_quantity": "", "name": "I", "unit": "cups", "whole_quantity": "1"],
                 ["grocery_section": "other", "partial_quantity": "", "name": "I", "unit": "cups", "whole_quantity": "2"]]
    
    let groupedDictionary = Dictionary(grouping: array, by: {$0["name"]!})
    var result = [[String:String]]()
    for (_, value) in groupedDictionary {
        if value.isEmpty { continue }
        else if value.count == 1 {
            result.append(value[0])
        } else {
            let totalQuantity = value.map{Int($0["whole_quantity"]!)!}.reduce(0, +)
            var mutableValue = value[0]
            mutableValue["whole_quantity"] = String(totalQuantity)
            result.append(mutableValue)
        }
    }