Home > Blockchain >  How can I reduce my array in Swift in the given format? Am not able to get the logic
How can I reduce my array in Swift in the given format? Am not able to get the logic

Time:05-02

I have a struct and an Array as follows

struct MyStruct : Codable {
   var name:String
   var slot:String
   var id: Int
}

struct NewStruct : Codable {
   var name:String
   var slot:[String]
   var id: Int
}

let data1 = MyStruct(name: "Ankit", slot: "1", id: 11)
let data2 = MyStruct(name: "Deric", slot: "1", id: 12)
let data3 = MyStruct(name: "Ankit", slot: "2", id: 11)
let data4 = MyStruct(name: "Deric", slot: "2", id: 12)
let data5 = MyStruct(name: "RandomName1", slot: "1", id: 13)
let data6 = MyStruct(name: "RandomName2", slot: "1", id: 14)
let data7 = MyStruct(name: "Ankit", slot: "3", id: 11)

var arrayOfData = [data,data2,data3,data4,data5,data6,data7]

am expecting that repeated name or say id should be merged and slot should have an array of the respective name or id, for reference am expecting result as

[
   NewStruct(name: "Ankit", slot: ["1","2","3"] ,id: 11),
   NewStruct(name: "Deric", slot:["1","2"], id: 12),
   NewStruct (name: "RandomName1", slot: ["1"], id: 13),
   NewStruct(name: "RandomName2", slot: ["1"], id: 14)
]

I need help please can someone help me out, am new to swift programming. I want to use this data to populate it in a collection view which is inside a Table view, where tableview shows me the name and collection view inside that table view shows me the all the slots for particular name, I did it in the react native i.e javascript code, using reduce method, not able to get it here though....

CodePudding user response:

You can use reduce(into:) to merge into a dictionary and then use the values of the dictionary

let merged = arrayOfData
    .reduce(into: [:]) {
        $0[$1.id, default: NewStruct(name: $1.name, slot: [], id: $1.id)].slot.append($1.slot)
    }
    .values
  • Related