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?
我需要保持所有的哈希:event_id和if:event_id是重复的保持最早的:created_at。我可以在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'}
]
2 个解决方案
#1
5
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 #uniq,特别是“按顺序遍历self,并保留第一个匹配项。”。
#2
3
Try this
array.group_by { |t| t[:event_id] }.map { |_,hash| hash.min_by { |t| t[:created_at]} }.sort_by {|t| -t[:created_at]}
#1
5
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 #uniq,特别是“按顺序遍历self,并保留第一个匹配项。”。
#2
3
Try this
array.group_by { |t| t[:event_id] }.map { |_,hash| hash.min_by { |t| t[:created_at]} }.sort_by {|t| -t[:created_at]}