Good day. There is a JSON array obtained from the network. Example of one element:

 { id: 5 title: "example" house: { houseID:"100" address:"example street" } } 

It is houseID to properly group items by houseID Many items can have the same houseID

 var arrRes = [[String:AnyObject]]() var sections = NSMutableArray() if let resData = swiftyJsonVar.arrayObject { self.arrRes = resData as! [[String:AnyObject]] } for json in self.arrRes { //нужно сгруппировать все элементы по house.addr if let data = json["house"] { let address = data["address"] as? String let houseID = data["houseID"] as? String print(address) } self.sections.addObject(json) } 

In the end, I want to see an array with one houseID, etc., etc., so that all this can then be passed to uiCollectionView for sections

  • So group or sort? And why by houseID , and not id ? - VAndrJ
  • more precisely grouped. why houseID ? that is my goal) - Konstantin
  • Those. on "houseID" add json want? - VAndrJ
  • Yes. And you need to place it in NSMutableArray (). to get the first element: {an array of all elements with one houseID} second element: {an array with another houseID}, etc. - Konstantin

1 answer 1

Disassemble immediately in the Dictionary :

 var dict = [String: [AnyObject]]() //ну либо NSMutableArray если так хотите вместо [AnyObject], но тогда не .append, a .addObject() for json in self.arrRes { if let data = json["house"] { let houseID = data["houseID"] as? String if let _ = dict[address] { dict[address]?.append(json) //.addObject(json) } else { dict[address] = [json] } } } 

UPD. Immediately in NSMuatableArray , I think it will be problematic to NSMuatableArray everything, more checks. Just after the formation of the Dictionary flip the arrays into NSMuatableArray :

 var arr = NSMutableArray() for elements in dict { arr.addObject(elements.1) } 
  • Thank you for the answer, but the output doesn’t quite turn out what was expected - Konstantin
  • @Konstantin from the comment "first element: {array of all elements with one houseID} second element: {array with another houseID}" understood that it is necessary so. Or do you want to add to houseID grouped by houseID NSMutableArray ? - VAndrJ
  • Или же Вы хотите в NSMutableArray добавлять сгруппированные по houseID NSMutableArray? That's right. I will try to describe it once again in a popular way: that is, to go over the whole main array and put all the elements on the shelves. each shelf has books with the same houseID :) - Konstantin
  • one
    @Konstantin, updated the answer, it can fit. - VAndrJ
  • @Konstantin, again did not understand what you want. Arrays are collected in one array. It turns out on an exit ((элементы с одним houseID),(элементы с другим houseID),(элементы с третьим houseID)) . What should be the output? - VAndrJ