2019-05-24
How to sum the value of same keys in an array with same type?
stackoverflow
Question

I have an array input:

[
  { type: 1, price: 50, discounted_price: 40 }, 
  { type: 2, price: 150, discounted_price: 140 },
  { type: 1, price: 40, discounted_price: 30 },
  { type: 2, price: 140, discounted_price: 130 }
]

and what an expected output:

[
  { 
     type: 1, 
     price: 90, # =>  50 + 40
     discounted_price: 70 # =>  40 + 30
  },
  {
     type: 2,
     price: 290, # => 150 + 140
     discounted_price: 270 # => 140 + 130
  }
]

I already tried reduce and group_by methods but cannot understand.

https://medium.com/@james.a.hughes/using-the-reduce-method-in-ruby-907f3c18ae1f

input.group_by { |item| 
  [item[:type]] 
}.values.flat_map { |items| 
  items.first.merge(price: items.sum { |h| h[:price].to_f }) 
}

it sums the price but i want both the price and discounted price.

Answer
1

You can use group_by and reduce:

input.group_by { |item| item[:type] }.flat_map do |_, collection|
  collection.reduce do |result, item| 
    result[:price] += item[:price]
    result[:discounted_price] += item[:discounted_price]
    result
  end
end

But using just reduce is enough as well:

input.reduce([]) do |result, item|
  result_i = result.find { |result_i| result_i[:type] == item[:type] }

  if result_i
    result_i[:price] += item[:price]
    result_i[:discounted_price] += item[:discounted_price]
    result
  else
    result << item 
  end
end
How to sum the value of same keys in an array with same type?
See more ...