0

i will build a UICollectionView with sections. The sections are based on the return value from json.category.

the json format is like:

[{"id":"1",
  "name":"Apple",
  "category":"Fruits"},
{"id":"2",
 "name":"Pie",
 "category":"Fruits"},
{"id":"3",
 "name":"Tomato",
 "category":"Vegetable"}]

I need a array filter hat the array is something like: (for sectionsItems and sectionNames)

CategorieNames[STRING] = ["Fruits","Vegetable"] // the section names from json.category
Fruits = [STRING] = ["Apple","Pie"]
Vegetables = [STRING] = ["Tomato"]

Categories.append[Fruits]
Categories.append[Vegetables]

Categories[[STRING]] = [[Fruits],[Vegetable]]
2

2 Answers 2

1

Try bellow code.

        let arrData = [["id": "1",
                        "name": "Apple",
                        "category": "Fruit"],
                       ["id": "2",
                        "name": "Pie",
                        "category": "Fruit"],
                       ["id": "3",
                        "name": "Tomato",
                        "category": "Vegetable"]]

        let categorieNames = Array(Set(arrData.map({$0["category"]!})))
        var arrResult:[[String]] = []
        for i in 0..<categorieNames.count {

            let categories = arrData.filter({$0["category"] == categorieNames[i]}).map({$0["name"]!})
            arrResult.append(categories)
        }
        print("result : \(arrResult)")

result : [["Apple", "Pie"], ["Tomato"]]

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks i‘ll test it
in playground it works like a charm! but I can't get it work with json data :-(
0

you can do it as follows:

let arrData = [["id": "1",
                "name": "Apple",
                "category": "Fruit"],

               ["id": "2",
                "name": "Pie",
                "category": "Fruit"],

               ["id": "3",
                "name": "Tomato",
                "category": "Vegetable"]]



var categorys = [[String]]()
var fruits = [String]()
var vegetable = [String]()

for data in arrData {

     if let category = data["category"] {
          if category == "Fruit"{
               if let aFruit = data["name"] {
                    fruits.append(aFruit)
               }
          }
          else if category == "Vegetable" {
               if let aVeggeie = data["name"] {
                     vegetable.append(aVeggeie)
               }
          }


}
}
categorys.append(fruits)
categorys.append(vegetable)

1 Comment

hi, thanks, but the categories are unknown. I can't check =="Fruit"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.