从Ruby数组中删除重复项并求和

时间:2015-06-12 18:52:16

标签: ruby-on-rails arrays ruby

我有以下数组数组[date,value]:

array = [[12 Mar 2015, 0], [12 Mar 2015, 5], [13 Mar 2015, 0], [14 Mar 2015, 49], [15 Mar 2015, 51], [15 Mar 2015, 10], [16 Mar 2015, 110], [17 Mar 2015, 0], [18 Mar 2015, 31], [19 Mar 2015, 47], [20 Mar 2015, 0], [21 Mar 2015, 0], [22 Mar 2015, 138], [22 Mar 2015, 10], [23 Mar 2015, 0]]

您可以看到有重复日期的数组。在按日期分组时如何对值进行求和?这就是我要找的东西:

array = [[12 Mar 2015, 5], [13 Mar 2015, 0], [14 Mar 2015, 49], [15 Mar 2015, 61],  [16 Mar 2015, 110], [17 Mar 2015, 0], [18 Mar 2015, 31], [19 Mar 2015, 47], [20 Mar 2015, 0], [21 Mar 2015, 0], [22 Mar 2015, 148],  [23 Mar 2015, 0]]

2 个答案:

答案 0 :(得分:3)

你的日子应该是

array = [["12 Mar 2015", 0], ["12 Mar 2015", 5], ["13 Mar 2015", 0], ["14 Mar 2015", 49], ["15 Mar 2015", 51], ["15 Mar 2015", 10], ["16 Mar 2015", 110], ["17 Mar 2015", 0], ["18 Mar 2015", 31], ["19 Mar 2015", 47], ["20 Mar 2015", 0], ["21 Mar 2015", 0], ["22 Mar 2015", 138], ["22 Mar 2015", 10], ["23 Mar 2015", 0]]

grouped = array.inject(Hash.new(0)) do |result, itm|
  result[itm.first] += itm.last
  result
end.to_a

答案 1 :(得分:2)

已更新

非常感谢@nathanvda,inject({}) do |hash, [time, index]|是我的错。无论如何,他的解决方案更清晰。

array.inject({}) do |hash, item|
  time, index = item.to_a
  hash[time] = hash.fetch(time, 0) + index
  hash
end.to_a