O
O
Ord EO2021-09-01 02:25:44
ruby
Ord EO, 2021-09-01 02:25:44

How to sum the values ​​of multiple hashes in ruby?

there is an array of several hashes (the number varies)
example

arr = [{name: 'd1', value: 10}, {name: 'd2', value: 30}, {name: 'd1', value: 5},  {name: 'd3', value:4}, {name: 'd2', value: 5}]
How to get an array from it with the sum of the same names
i.e. should be something like this
arr = [{name: 'd1', value: 15], {name: 'd2', value: 35}, {name: 'd3', value: 4}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2021-09-01
@OrdeO

arr
  .group_by{|n| n[:name]}
  .map{|n| { name: n[0], value: n[1].sum{|m| m[:value]} }}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question