简体   繁体   English

按日期优化哈希的分组数组

[英]Optimize grouping array of hashes by date

Given array 给定数组

[
  {date: '2014-01-01', a: 5, b:1},
  {date: '2014-01-01', xyz: 11},
  {date: '2014-10-10', qbz: 5},
  {date: '2014-10-10', v: 4, q: 1, strpm: -99}
]

I want to group by date and output an array of hashes 我想按日期分组并输出哈希数组

ouput = [
 {date: 2014-01-01, a: 5, b:1, xyz: 11 },
 {date: 2014-10-10, qbz: 5, v: 4, q: 1, strpm: -99},
]

I am solving it in Ruby and have a solution but it seems inefficient. 我正在Ruby中解决它,并且有解决方案,但效率似乎很低。

def arrayt(inputarray)
    outputarray=[];
    inputarray.each do |x|
        tindex = includes(outputarray,x[:date])
        if tindex == -1
            outputarray.push(x)
        else
            outputarray[tindex].merge!(x)
        end
    end
    return outputarray
end

def includes(array,date)
    array.each_with_index do |temp,index|
        if date==temp[:date]
            return index
        end
    end
    return -1
end

Any help with a more elegant solution would be appreciated 任何更优雅的解决方案的帮助将不胜感激

[
  {date: '2014-01-01', a: 5, b:1},
  {date: '2014-01-01', xyz: 11},
  {date: '2014-10-10', qbz: 5},
  {date: '2014-10-10', v: 4, q: 1, strpm: -99}
]
.group_by(&:first).map{|_, v| v.inject(:merge)}

Here's a way that employs the form of Hash#update (aka merge! ) that uses a block to determine the values of keys that are present in both hashes being merged: 这是一种采用Hash#update的形式(也称为merge! )的形式,该形式使用一个块来确定要合并的两个哈希中存在的键的值:

arr.each_with_object({}) { |g,h|
  h.update({ g[:date]=>g }) { |_,ov,nv| ov.merge(nv) } }.values

To wit: 以机智:

    hash = arr.each_with_object({}) { |g,h|
      h.update({ g[:date]=>g }) { |_,ov,nv| ov.merge(nv) } }
    #=>{"2014-01-01"=>{:date=>"2014-01-01", :a=>5, :b=>1, :xyz=>11},
    #   "2014-10-10"=>{:date=>"2014-10-10", :qbz=>5, :v=>4, :q=>1, :strpm=>-99}} 
    hash.values
    #=> [{:date=>"2014-01-01", :a=>5, :b=>1, :xyz=>11},
    #    {:date=>"2014-10-10", :qbz=>5, :v=>4, :q=>1, :strpm=>-99}] 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM