I have the following array that contains a searched product by the user; once searched, the tags of the product is also stored in the searchTags array like below:
searchedTags = [ [product : [tagA, tagB, tagC, tagD, tagH ]] ]
Now I have a array list of all products that contains different tags for each product:
productTagsArray = [ [product1 : [tagA, tagB, tagC, tagD]],
[product2 : [tagC, tagD, tagE, tagF, tag H]],
[product3 : [tagH, tagI, tagJ]],
[product4 : [tagK, tagL, tagM]],
...
]
Now I would like to check and compare the tags from the searched product in searchedTags
with each product in productTagsArray
. Once compared, I'd like to make a new array of products sorted by the COUNTS of tags matched (high to low) with the searched products. If there are no tags matching I do not want to include them in the new variable. I would like to populate the result of this sorted match like below:
sortedProductsByCount = [[productId : product1, numberOfTagsMatched : 4],
[productId : product2, numberOfTagsMatched : 2],
[productId : product1, numberOfTagsMatched : 1]
]
Edit: This is what I have written for when the user click on the search result in tableview:
var productsTagCount: [[String:Any]] = [[:]]
for tags in searchedProductTags {
for tag in tags {
for productArray in productTagsArray {
for product in productArray {
var tagCount: Int = 0
for productTag in product.value {
if productTag == tag {
tagCount = tagCount + 1
}
}
let data: [String : Any] = [
"productId": product.key,
"tagCount": tagCount
]
productsTagCount.append(data)
}
}
}
}
Is there a better way? How can I accomplish the sortedProductByCount
array?
Here is how I fixed it. Had to change my codes quite a bit.
var productTagsArray : [[String : [String]]] = [[:]]
var productTagCount : [String : Int] = [:]
var sortedProductTagCount: [Int : [String : Int]] = [:]
let searchedProductTags = searchResults[indexPath.row].values
for productArray in productTagsArray {
for product in productArray {
let productId: String = product.key
var tagCount: Int = 0
for productTag in product.value {
for searchedTags in searchedProductTags {
for searchedTag in searchedTags {
if productTag == searchedTag {
tagCount = tagCount + 1
}
}
}
}
if tagCount != 0 {
productTagCount[productId] = tagCount
}
}
}
//Make an array with sorted tagscount
let sortedProductTagCountVar = productTagCount.sorted{ $0.value > $1.value }
var productSortIndex: Int = 0
for (k,v) in sortedProductTagCountVar {
productSortIndex = productSortIndex + 1
sortedProductTagCount[productSortIndex, default: [:]][k] = v
}