简体   繁体   中英

Sorting Ruby Array of hashes with 2 date keys

I have an array of hashes with 2 keys that have timestampvalues (YYYY/MM/DD/HH/MM/SS) : start_date and end_date .

Array_initial = [
    { :started_at => 20201105143200, :ended_at => 20201105143900 },
    { :started_at => 20201105142900, :ended_at => 20201105143300 },
    { :started_at => 20201105142800, :ended_at => 20201105143000 },
]

I want to convert this array of hashes into an array of arrays but sorted by comparing both started_at and ended_at timestamps. So the result would be this:

Array_final = [
[:started_at, 20201105142800], 
[:started_at, 20201105142900], 
[:ended_at, 20201105143000], 
[:started_at, 20201105143200], 
[:ended_at, 20201105143300], 
[:ended_at, 20201105143900]
]

Can't figure out how to do that...

First you want to change the structure from this:

a = [
  { :started_at => 20201105143200, :ended_at => 20201105143900 },
  { :started_at => 20201105142900, :ended_at => 20201105143300 },
  { :started_at => 20201105142800, :ended_at => 20201105143000 },
]

to something that matches the structure of your result:

[
  [key, timestamp],
  [key, timestamp],
  ...
]

so that you can sort it.

Enumerable#flat_map and Hash#to_a will do that nicely:

a.flat_map(&:to_a)
# [
#   [:started_at, 20201105143200],
#   [:ended_at,   20201105143900],
#   [:started_at, 20201105142900],
#   [:ended_at,   20201105143300],
#   [:started_at, 20201105142800],
#   [:ended_at,   20201105143000]
# ]

Then sort by the last element and you're done:

a.flat_map(&:to_a).sort_by(&:last)
# [
#   [:started_at, 20201105142800],
#   [:started_at, 20201105142900],
#   [:ended_at,   20201105143000],
#   [:started_at, 20201105143200],
#   [:ended_at,   20201105143300],
#   [:ended_at,   20201105143900]
# ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM