简体   繁体   中英

How to filter array of hashes by two pairs of `key => value` in ruby?

I have an array of hashes:

array = [
{:created_at => 1520913341, :event_id => '111', :album_id => '123'},
{:created_at => 1520740541, :event_id => '234', :album_id => '999'},
{:created_at => 1520654141, :event_id => '111', :album_id => '777'},
{:created_at => 1520394941, :event_id => '233', :album_id => '444'},
{:created_at => 1520049341, :event_id => '890', :album_id => '765'}
 ]

i need to keep hashes with all :event_id and if :event_id is duplicated keep the one with earliest :created_at .How can i do that in ruby?

i expect to get in the response following:

[
{:created_at => 1520740541, :event_id => '234', :album_id => '999'},
{:created_at => 1520654141, :event_id => '111', :album_id => '777'},
{:created_at => 1520394941, :event_id => '233', :album_id => '444'},
{:created_at => 1520049341, :event_id => '890', :album_id => '765'}
 ]
array.sort_by { |h| h[:created_at] }.uniq { |h| h[:event_id] }
  #=> [{:created_at=>1520049341, :event_id=>"890", :album_id=>"765"},
  #    {:created_at=>1520394941, :event_id=>"233", :album_id=>"444"},
  #    {:created_at=>1520654141, :event_id=>"111", :album_id=>"777"},
  #    {:created_at=>1520740541, :event_id=>"234", :album_id=>"999"}]

See Array#uniq , in particular, " self is traversed in order, and the first occurrence is kept.".

尝试这个

array.group_by { |t| t[:event_id] }.map { |_,hash| hash.min_by { |t| t[:created_at]} }.sort_by {|t| -t[:created_at]}

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