How to condense summable metrics to a unique identifier in a ruby table

后端 未结 3 645
挽巷
挽巷 2021-01-21 13:43

I\'m trying to condense summable metrics to a unique identifier in a ruby table.

I have the following table:

[[\"id1\", 123], [\"id2\", 234], [\"id1\", 3         


        
相关标签:
3条回答
  • 2021-01-21 14:16

    I think the other answerers are overthinking this. You can do this with just one operation, each_with_object, and a Hash:

    metrics = [["id1", 123], ["id2", 234], ["id1", 345]]
    
    metrics.each_with_object(Hash.new(0)) do |(id, val), sums|
      sums[id] += val
    end
    # => {"id1"=>468, "id2"=>234}
    

    If you want an Array instead of a Hash at the end just call to_a on the result, but there are few compelling reasons to do so.

    0 讨论(0)
  • 2021-01-21 14:16

    As condensed as it can get.

    array = [["id1", 123],["id2", 234], ["id1", 345]]
    array.group_by(&:first).collect{|key,values| [key,values.reduce(0) {|sum,a| sum+a[1]}]}
    
    0 讨论(0)
  • 2021-01-21 14:17
    summable_metrics = [["id1", 123],["id2", 234], ["id1", 345]]
    
    summable_metrics.group_by(&:first).map do |k, v|
      [k, v.map(&:last).reduce(:+)]
    end
    
    => [["id1", 468], ["id2", 234]] 
    
    0 讨论(0)
提交回复
热议问题