TFD Dan
TFD Dan

Reputation: 11

swift - Find duplicate dictionaries in an array

I am looking to count the number of duplicate dictionaries inside an array/dictionary and return an array with the number of duplicate ID strings. Below is a sample of the array I have.

struct item {
   var id = [String:String]()
   var name = [String:String]()
   var price = [String:Int]()
}

array = [{ "id": "xxxx1", "name": "prodName1", "price": 15},
           "id": "xxxx2", "name": "prodName2", "price": 20}
           "id": "xxxx1", "name": "prodName1", "price": 15}]

var numbered = [item.id:Int]
array.forEach{ (items) in
    numbered[items] = numbered[items] ?? 0 + 1                     
}

I've tried following a foreach counter (with a struct) but I can't seem to get it set up properly. I'm looking to get a result like this:

result = ["xxxx1": 2, "xxxx2": 1]

Upvotes: 1

Views: 59

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236315

You need to first fix your structure declaration. Then create an array with your structure elements. This will make your life much easier. Then you can simply use reduce to count there occurrences:

struct Item {
   let id: String
   let name: String
   let price: Int
}

let array = [("xxxx1", "prodName1", 15),
             ("xxxx2", "prodName2", 20),
             ("xxxx1", "prodName1", 15)].map(Item.init)

let result = array.reduce(into: [:]) { $0[$1.id, default: 0] += 1 }
result // ["xxxx2": 1, "xxxx1": 2]

Upvotes: 1

Related Questions