Return Objects/Hashes 数组按属性排序

Return Array of Objects/Hashes sorted by attributes

我有一个对象数组,在此示例中表示为散列:

[
 { "mid" => 123, "updated" => "2015-05-05 05:05:05"}
 { "mid" => 456, "updated" => "2015-05-05 05:06:05"}
 { "mid" => 789, "updated" => "2015-05-05 05:05:05"}
 { "mid" => 123, "updated" => "2015-05-05 05:05:07"}
 { "mid" => 456, "updated" => "2015-05-05 05:05:05"}
]

而且我只需要取回具有唯一mid的元素,在选择唯一对象的过程中,需要考虑时间戳,其中更高的日期时间是return。所以我的示例结果将是:

[
 { "mid" => 456, "updated" => "2015-05-05 05:06:05"}
 { "mid" => 789, "updated" => "2015-05-05 05:05:05"}
 { "mid" => 123, "updated" => "2015-05-05 05:05:07"}
]

我尝试了几种不同的方法,但我的逻辑有问题,我总是得到 20 个对象而不是 3 个。这是我的代码:

res = []
queue.length.times do
    a = queue.pop
    queue.each do |job|
        if a.mid == job.mid
            if DateTime.parse(a.updated) >= DateTime.parse(a.updated)
                res << a
            end
        else
            res << a
        end
    end
    queue << a
end

有什么想法吗?

假设您在 arr 中输入:

arr.group_by do |h| 
  h['mid']                   # group same mids
end.values.map do |all|
  all.max_by do |h|
    Date.parse h['updated']  # pick latest by date
  end
end

#⇒ [
#    {"mid"=>123, "updated"=>"2015-05-05 05:05:07"},
#    {"mid"=>456, "updated"=>"2015-05-05 05:06:05"},
#    {"mid"=>789, "updated"=>"2015-05-05 05:05:05"}
# ]

请避免使用 ruby 语法编写 phpish 代码。

UPD 感谢 Cary Swoveland,sort_by+last 减少到 max_by

您可以使用类似的东西:

queue.sort_by { |r| DateTime.parse(r[:updated]) }.reverse.uniq { |r| r[:mid] }

# => [{:mid=>456, :updated=>"2015-05-05 05:06:05"}, {:mid=>123, :updated=>"2015-05-05 05:05:07"}, {:mid=>789, :updated=>"2015-05-05 05:05:05"}]

其中 queue 是您的输入数组。