Sum of values inside Array
I have array like
[{:name=>"test 1",
:sku=>"HG-22LR",
:data1=>5,
:data2=>5,
},
{:name=>"test 1",
:sku=>"RF-22LR",
:data1=>2,
:data2=>2,
}]
I need to combine the value of data1 and data2.
output like:
[
{:name=>"test 1",
:sku=>"HG-22LR",
:data1=>7,
:data2=>7,
}
]
Solution 1:
data:
data = [{:name => "test 1",
:sku => "HG-22LR",
:data1 => 5,
:data2 => 5,
},
{:name => "test 1",
:sku => "RF-22LR",
:data1 => 2,
:data2 => 2,
}]
possibilities:
data.group_by{ |record| [record[:name], record[:sku]] }.map do |group, records|
{
name: group[0],
sku: group[1],
data1: records.sum { |d1| d1[:data1] },
data2: records.sum { |d2| d2[:data2] }
}
end
=> [{:name=>"test 1", :sku=>"HG-22LR", :data1=>5, :data2=>5}, {:name=>"test 1", :sku=>"RF-22LR", :data1=>2, :data2=>2}]
or if you don't need to separate by SKU, and you want to join a list of SKUs :
data.group_by { |record| [record[:name]] }.map do |group, records|
{
name: group[0],
sku: records.map { |d0| d0[:sku] }.uniq.join(','),
data1: records.sum { |d1| d1[:data1] },
data2: records.sum { |d2| d2[:data2] }
}
end
=> [{:name=>"test 1", :sku=>"HG-22LR,RF-22LR", :data1=>7, :data2=>7}]
if you don't like #join
, you could use #first
, #last
, #max
, #min
, etc.