0

I have a List that I want to divide according to atributes that I want to get. For example. I if have this list I want to create 3 different lists using a main list.

  var companiesf = [
    Directory(directoryId: 1, fullname: "Jose Luis", company: "A"), 
    Directory(directoryId: 2, fullname: "Fernando", company: "A"), 
    Directory(directoryId: 3, fullname: "Maria", company: "B"), 
    Directory(directoryId: 4, fullname: "Rodrigo", company: "B"),
    Directory(directoryId: 5, fullname: "Miguel", company: "C")
  ]

Finally, I want to get this result

 var listA = [
     Directory(directoryId: 1, fullname: "Jose Luis", company: "A"), 
     Directory(directoryId: 2, fullname: "Fernando", company: "A")
   ]


   var listB = [
    Directory(directoryId: 3, fullname: "Maria", company: "B"), 
    Directory(directoryId: 4, fullname: "Rodrigo", company: "B")
   ]


   var listC = [
    Directory(directoryId: 5, fullname: "Miguel", company: "C")
   ]

but I don't know how to create array objects automatically

Thank you so much!

Antonio Labra
  • 1,694
  • 2
  • 12
  • 21

1 Answers1

0

You can create your company arrays by creating a grouped dictionary

let groupedByCompany = Dictionary(grouping: companiesf, by: {$0.company})

and then create your arrays from it

let listA = grouped["A", default: []]
let listB = grouped["B", default: []]
let listC = grouped["C", default: []]

another option is to use filter

let listA = companiesf.filter {$0.company == "A"}
let listB = companiesf.filter {$0.company == "B"}
let listC = companiesf.filter {$0.company == "C"} 
Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52