Group and sum array of hashes by date
来源:互联网 发布:python微信公众号爬虫 编辑:程序博客网 时间:2024/04/28 19:03
I have an array of hashes like this:
[{:created=>Fri, 22 Jan 2014 13:02:13 UTC +00:00, :amount=>20}, {:created=>Fri, 27 Jan 2014 13:14:57 UTC +00:00, :amount=>15}, {:created=>Fri, 27 Jan 2014 14:42:40 UTC +00:00, :amount=>10}, {:created=>Fri, 28 Jan 2014 15:26:58 UTC +00:00, :amount=>10}, {:created=>Fri, 28 Jan 2014 15:30:18 UTC +00:00, :amount=>20}, {:created=>Fri, 31 Jan 2014 15:32:46 UTC +00:00, :amount=>50}, {:created=>Fri, 31 Jan 2014 15:33:29 UTC +00:00, :amount=>40}]
I'd like to group those hashes by date and sum the amounts. So, in my example, the output would be:
[{:created=>"2014-01-22", :amount=>20}, {:created=>"2014-01-27", :amount=>25}, {:created=>"2014-01-28", :amount=>30}, {:created=>"2014-01-31", :amount=>90}]
a.group_by { |h| Date.parse h[:created] }.map { |k,v|{:created => k.to_s,:amount => v.map {|h1| h1[:amount]}.inject(:+)}}require 'date'a = [{:created=> 'Fri, 22 Jan 2014 13:02:13 UTC +00:00', :amount=>20}, {:created=>'Fri, 27 Jan 2014 13:14:57 UTC +00:00', :amount=>15}, {:created=>'Fri, 27 Jan 2014 14:42:40 UTC +00:00', :amount=>10}, {:created=>'Fri, 28 Jan 2014 15:26:58 UTC +00:00', :amount=>10}, {:created=>'Fri, 28 Jan 2014 15:30:18 UTC +00:00', :amount=>20}, {:created=>'Fri, 31 Jan 2014 15:32:46 UTC +00:00', :amount=>50}, {:created=>'Fri, 31 Jan 2014 15:33:29 UTC +00:00', :amount=>40}]
0 0
- Group and sum array of hashes by date
- ruby - group by repeating key of multiple hashes
- How to SUM and GROUP BY of JSON data?
- JavaScript SUM and GROUP BY of JSON data
- ruby merge array of hashes based on the key and order it by number of key/value pair
- Sorting a mixed array of hashes and strings
- How to combine the value of multiple hashes within an array by the same key
- How do I sort an array of hashes by a value in the hash?
- //使用hibernate,实现group by and sum and count
- Extracting Data from array of hashes Ruby
- Ruby converting array of hashes to array of arrays
- sum 与 group by
- group by,distinct,sum
- Test of MV FAST refresh with Sum and group
- Group by and Order by
- How to sort an array of hashes into hashes with multiple values for a key?
- Rails mapping array of hashes onto single hash
- group by 的 sum 求和
- Windows DIB文件操作详解-4.使用DIB Section
- 精图规范1.0----23 扩展性 Extensibility
- 【LeetCode】N-Queens
- POJ 2965 The Pilots Brothers' refrigerator
- netlink中用到的结构体和宏
- Group and sum array of hashes by date
- CentOS 防火墙开启80端口
- NYOJ-264 国王的魔镜
- 香港中文大学某门研究生课程的课程提纲
- Android 基础理论 day02
- WPF自定义Popup和弹出菜单
- 以后不用在担心机密泄露了,io技术帮你分割文件,只有懂技术的你,懂得如何看文件
- 静态导入import static ....
- Array to hash with multiple keys