简体   繁体   中英

Group array of hashes by key

I have an array consisting of hashes in the following form:

[
  {:user=>"mike" etc},
  {:user=>"mike" etc},
  {:user=>"peter" etc},
  {:user=>"joe" etc}
]

Are there any convenient ways to split the group according to the value of user key? The final result should be something like this:

[
  [{:user=>"mike" etc}, {:user=>"mike" etc}],
  [{:user=>"peter" etc}],
  [{:user=>"joe" etc}]
]

使用group_by

array.group_by{|h| h[:user]}.values

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