0

I have an array of dictionaries like this:

var uidTimestampsNotSorted = [[String: Timestamp]]()

and I want to sort the dictionaries by the value of the dictionary Timestamp, how can I achieve that?

StackGU
  • 868
  • 9
  • 22
  • Can you show some sample inputs and outputs? – Sweeper Apr 09 '21 at 12:07
  • But there is only one key "Timestamp", or there are multiple keys, and you also have to find the key corresponding to the "Timesamp". Could you share some input sample? – Larme Apr 09 '21 at 12:28
  • there's only one key of type Timestamp and I need to order the array of dictionaries from the earliest timestamp to the latest – StackGU Apr 09 '21 at 13:49

1 Answers1

0

If you mean you want to sort the timestamps themselves, then something like this example might do it:

let dicts: [[String: Int]] = [
    ["a":1, "b": 2, "c": 3],
    ["A":10, "B": 20, "C": 30],
    ["AA":100, "BB": 200, "CC": 300],
]

let vs = dicts.flatMap(\.values).sorted(by: >)

With an appropriate sorting function

Shadowrun
  • 3,572
  • 1
  • 15
  • 13
  • I need to sort the array of dictionaries knowing that the value is only one timestamp for dictionary. I need to order the key value pair starting from the earliest timestamp finishing with the latest – StackGU Apr 09 '21 at 13:51
  • 1
    like this? let vs = dicts.sorted { (lhs, rhs) -> Bool in (lhs["timestamp"] ?? 0) < (rhs["timestamp"] ?? 0) } – Shadowrun Apr 09 '21 at 14:01
  • thank you! it works – StackGU Apr 09 '21 at 14:34