在字典数组中获取重复值。迅速

时间:2017-09-05 04:12:48

标签: arrays swift swift3

我有一个像这样的数组

[
    ["itm_id": 4, "itm_name": Chicken],
    ["itm_id": 4, "itm_name": Chicken],
    ["itm_id": 4, "itm_name": Chicken],
    ["itm_id": 7, "itm_name": Cat]
]

我有这个字典数组,我试图用字典中的值对它们进行分组。所以在我上面的例子中,我想知道创建一个字典,知道我用重复键有多少字典:

[["item_id" : 4, count: 3], ["item_id" : 7, count: 1]]

itm_id: 4重复3次,因此计数为3,itm_id: 7仅重复一次。

我怎样才能实现

3 个答案:

答案 0 :(得分:1)

我建议你创建一个项目数组的struct而不是像这样的字典

struct Item{
    var itemID : Int
    var name : String

    init(dictionary:[String:Any]) {
        itemID = dictionary["itm_id"] as? Int ?? 0
        name = dictionary["itm_name"] as? String ?? ""
    }
}

获得Items数组后,您可以将特定项ID的元素映射为数组以获取计数并将其从数组中删除。看看下面的代码。不是最干净的实现,但它可以帮助您解决问题。

func countDuplicates(){
    let dictionary = [["itm_id": 4, "itm_name": "Chicken"],["itm_id": 4, "itm_name": "Chicken"],["itm_id": 4, "itm_name": "Chicken"],["itm_id": 7, "itm_name": "Cat"]]
    var items = [Item]()
    var countArray = [[String:Any]]()
    dictionary.forEach{
        items.append(Item(dictionary: $0))
    }
    while items.count > 0 {
        if let firstItem = items.first{
            let duplicateItems = items.filter{$0.itemID == firstItem.itemID}
            var countDictionary = [String:Any]()
            countDictionary["itm_id"] = firstItem.itemID
            countDictionary["count"] = duplicateItems.count
            countArray.append(countDictionary)
            items = items.filter{$0.itemID != firstItem.itemID}
        }
    }
    print(countArray)
}

这将打印[["itm_id": 4, "count": 3], ["itm_id": 7, "count": 1]]

我认为ChickenCat是字符串。如果它们不是字符串而是类类型,您可以将Item结构重写为类似

class Animal{}

class Chicken:Animal{}

class Cat:Animal{}

struct Item<T:Animal>{
    var itemID : Int
    var name : String
    var animal : Animal

    init(dictionary:[String:Any],animal:T) {
        itemID = dictionary["itm_id"] as? Int ?? 0
        name = dictionary["itm_name"] as? String ?? ""
        self.animal = animal
    }
}

然后你可以初始化项目,如

yourItem = Item(dictionary:yourDictionary,animal:Cat())

答案 1 :(得分:0)

// Swift 3.1

选项1:使用词典

func countRepeats() -> [[String: Int]] {
    var repeats = [Int: Int]()
    arr.forEach { item in
        if let id = item["itm_id"] as? Int {
            repeats[id] = repeats[id] == nil ? 1 : repeats[id]! + 1
        }
    }
    return repeats.map {["item_id" : $0.key, "count": $0.value]}
}

print(countRepeats()) // [["item_id": 4, "count": 3], ["item_id": 7, "count": 1]]

选项2:建议使用Struct而不是Dictionary

public struct ItemCount {
    let id: Int
    let count: Int
}

func countRepeats() -> [ItemCount] {
    var repeats = [Int: Int]()
    arr.forEach { item in
        if let id = item["itm_id"] as? Int {
            repeats[id] = repeats[id] == nil ? 1 : repeats[id]! + 1
        }
    }
    return repeats.map {ItemCount(id:$0.key, count: $0.value)}
}

print(countRepeats())

答案 2 :(得分:0)

我建议在类(或Structs)中操作你的数据,但是如果你必须使用字典数组,这是获得计数的一种方法:

{{1}}