3

我需要图表的值,并且我希望合并具有相同日期的所有值。

这是我现在拥有的数组:

[ ['2012-10-09', 1], ['2012-10-09', 2], ['2012-10-10', 1], ['2012-10-10', 4], ['2012-10-10', 1], ['2012-10-11', 3] ]

我想要的结果:

[ ['2012-10-09', 3], ['2012-10-10', 6], ['2012-10-11', 3] ]

有没有一种简单的方法可以做到这一点?

4

4 回答 4

4

就那么简单:

a.inject({}) { |h,(date, count)| h[date] ||= 0; h[date] += count; h }.to_a
于 2012-10-10T23:43:17.770 回答
3

使用 rails 的group_by,您可以这样做:

x = [ ['2012-10-09', 1], ['2012-10-09', 2], ['2012-10-10', 1], ['2012-10-10', 4], ['2012-10-10', 1], ['2012-10-11', 3] ]
x.group_by(&:first).map { |k, v| [k, v.map(&:last).inject(0,&:+)] }
于 2012-10-10T22:45:01.727 回答
1

Mapreduce 是一个非常强大的工具,但是理解起来有点复杂。所以使用 sum 方法也是一样的:

x = [ ['2012-10-09', 1], ['2012-10-09', 2], ['2012-10-10', 1], ['2012-10-10', 4], ['2012-10-10', 1], ['2012-10-11', 3] ]
expected = [ ['2012-10-09', 3], ['2012-10-10', 6], ['2012-10-11', 3] ]

x.group_by(&:first).map { |k, v| [k, v.sum(&:last)] }.should == expected
于 2012-10-10T22:59:14.420 回答
0

它类似于罗马的答案,但使用三元运算符

a.inject({}) { |h,(date,count)| h.has_key?(date) ? h[date] += count : h[date] = count; h }.to_a
于 2012-10-11T04:25:39.257 回答