mardi 5 mai 2015

Group by date and reduce an array to create a new one

I have this array:

> source

# =>
[[Fri, 13 Mar 2015, [24.2]],
 [Tue, 17 Mar 2015, [0.01, 8.26]],
 [Mon, 16 Mar 2015, [0.01, 0.01, 0.01, 0.01]],
 [Mon, 16 Mar 2015, [0.01, 0.01]],
 [Fri, 13 Mar 2015, [24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2]],
 [Fri, 13 Mar 2015, [24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2, 24.2]],
 [Mon, 16 Mar 2015, [15.95]],
 [Thu, 12 Mar 2015, [352429.0, 35242900.0, 3.0]]
]

How can I create this one out of it:

[
  [Thu, 12 Mar 2015, aaa]
  [Fri, 13 Mar 2015, bbb],
  [Mon, 16 Mar 2015, ccc],
  [Tue, 17 Mar 2015, ddd]
]

Where aaa, bbb ... are the sums of the elements with the same date. Note that [Thu, 12 Mar 2015, aaa]

are 2 elements, not 3: 12 Mar 2015 and aaa

What I tried:

source.group_by { |x| x[0] }.reduce(0) # sum up all the element except the 1st one which is a date - how?

Aucun commentaire:

Enregistrer un commentaire