1

How could I sort the following associative array:

[
  ["name": "Zone A", "type": "1"], 
  ["name": "Zone B", "type": "2"], 
  ["name": "Zone C", "type": "1"],
  ["name": "Zone D", "type": "3"], 
  ["name": "Zone E", "type": "2"], 
  ["name": "Zone F", "type": "3"],
  ["name": "Zone G", "type": "1"], 
  ["name": "Zone H", "type": "2"]
]

to result in the following - sorted by TYPE:

[
  ["name": "Zone A", "type": "1"], 
  ["name": "Zone C", "type": "1"],
  ["name": "Zone G", "type": "1"], 
  ["name": "Zone B", "type": "2"], 
  ["name": "Zone E", "type": "2"], 
  ["name": "Zone H", "type": "2"]
  ["name": "Zone D", "type": "3"],       
  ["name": "Zone F", "type": "3"],
] 

Thanks in advance!

iSofia
  • 1,412
  • 2
  • 19
  • 36

1 Answers1

2

Use sort

var a = [
  ["name": "Zone A", "type": "1"], 
  ["name": "Zone B", "type": "2"], 
  ["name": "Zone C", "type": "1"],
  ["name": "Zone D", "type": "3"], 
  ["name": "Zone E", "type": "2"], 
  ["name": "Zone F", "type": "3"],
  ["name": "Zone G", "type": "1"], 
  ["name": "Zone H", "type": "2"]
]

a.sort { (v1, v2) -> Bool in
    return v1["type"]! < v2["type"]!
}

//or:
//a.sort { $0["type"]! < $1["type"]! }

print("\(a)")

See also: Swift how to sort array of custom objects by property value

And sort & sorted: https://developer.apple.com/documentation/swift/array/2296801-sort

  • sort: Sorts the collection in place.
  • sorted: Returns the elements of the sequence, sorted.
shawn
  • 4,305
  • 1
  • 17
  • 25
  • Thank you. That's brilliant, shawn. I should elaborate, for clarity, that the structure in the OP is actually an array, and not a dictionary (mis-tagged). Accordingly, this **sort** solution works perfectly. Always foggy about these terminologies. – iSofia Nov 19 '18 at 10:54
  • PHP uses the concept `Associative Array` more and Swift uses the concept `Dictionary` more, they are the same. See here: http://iosdose.com/wp/2017/08/22/swift-dictionary/ . And about `sort` and `sorted`: the `sort` does sort on the original array and changes it. `sorted` doesn't change the original array and return a newly created sorted array. – shawn Nov 19 '18 at 12:36