zoukankan      html  css  js  c++  java
  • Group and sum array of hashes by date

    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}]
    
    
    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}]
     a.group_by { |h| Date.parse h[:created] }.map { |k,v|{:created => k.to_s,:amount => v.map {|h1| h1[:amount]}.inject(:+)}}
  • 相关阅读:
    SQL的介绍及MySQL的安装
    git中级技能
    git基本用法
    git基本语法
    出租车数据分析
    使用Spark MLlib进行情感分析
    增量式编码器专题
    vue-loader的简单例子
    node爬虫(转)
    fs-extra 文件管理
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4490936.html
Copyright © 2011-2022 走看看