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!

2
  • You don't sort an associative array. It makes no sense. You copy elements to a regular array and sort it. Commented Nov 19, 2018 at 6:28
  • 1
    You should have that array as an array of a struct with name and type instead of a dictionary. Commented Nov 19, 2018 at 6:32

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

2 Comments

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.
PHP uses the concept Associative Array more and Swift uses the concept Dictionary more, they are the same. See here: 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.