Search code examples
iosuicollectionviewsections

swift 4 split array and filter


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]]

Solution

  • 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"]]