简体   繁体   中英

Ruby on Rails - Gather hashes with same specific value

Given a an array of hashes where every hash is like {"date":"date_value", "slots":[slots_value]} , I'd like to gather hashes with the same dates on one hash and merge slots arrays.

Example input:

[{"date" : "2016/23/12", "slots" : ["a","b"]},
 {"date" : "2016/23/12", "slots" : ["c","d","e"]},
 {"date" : "2016/24/12", "slots" : ["x"]}
]

Example output:

[{"date" : "2016/23/12", "slots" : ["a","b","c","d","e"]},
 {"date" : "2016/24/12", "slots" : ["x"]}
]

Enumerable#group_by is a very powerful tool for Hashes and Arrays :

input = [
  {"date" => "2016/23/12" ,  "slots" => ["a","b"]},
  {"date" => "2016/23/12", "slots" => ["c","d","e"]},
  {"date" => "2016/24/12", "slots" => ["x"]}
]

puts input.group_by{|h| h["date"]}.map{|date, hashes|
  {
    "date" => date,
    "slots" => hashes.map{|h| h["slots"]}.flatten
  }
}
#=> {"date"=>"2016/23/12", "slots"=>["a", "b", "c", "d", "e"]}
#   {"date"=>"2016/24/12", "slots"=>["x"]}

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