Skip to content

Instantly share code, notes, and snippets.

@francirp
Created March 6, 2015 21:37
Show Gist options
  • Save francirp/981bd60831e335d5836d to your computer and use it in GitHub Desktop.
Save francirp/981bd60831e335d5836d to your computer and use it in GitHub Desktop.
Group an array two levels deep
module Components::Extensions::GroupBy
def group_by_two_levels(args = {})
array, first, second = [args[:array], args[:first], args[:second]]
hash = array.group_by do |obj|
obj.respond_to?(first) ? obj.send(first) : obj[first]
end
hash.each do |first, obj_array|
hash[first] = obj_array.group_by do |obj|
obj.respond_to?(second) ? obj.send(second) : obj[second]
end
end
hash
end
end
@francirp
Copy link
Author

francirp commented Mar 6, 2015

Example:

include Components::Extensions::GroupBy

weather_data = [
  {
    "station"=>"GHCND:ZI000067983", 
    "value"=>119, 
    "attributes"=>",,S,", 
    "datatype"=>"PRCP", 
    "date"=>"2015-01-01T00:00:00"
  }, 
  { "station"=>"GHCND:ZI000067983", 
    "value"=>217, 
    "attributes"=>",,S,", 
    "datatype"=>"TMAX", 
    "date"=>"2015-01-01T00:00:00"
  } # actual dataset has many more records
]

my_newly_grouped_hash = group_by_two_levels(array: weather_data, first: "date", second: "datatype")

{ 
  "2015-01-01T00:00:00" => {
    "PRCP"=>[{"station"=>"GHCND:ZI000067983", "value"=>119, "attributes"=>",,S,", "datatype"=>"PRCP", "date"=>"2015-01-01T00:00:00"}], 
    "TMAX"=>[{"station"=>"GHCND:ZI000067983", "value"=>217, "attributes"=>",,S,", "datatype"=>"TMAX", "date"=>"2015-01-01T00:00:00"}], 
    "TMIN"=>[{"station"=>"GHCND:ZI000067983", "value"=>171, "attributes"=>",,S,", "datatype"=>"TMIN", "date"=>"2015-01-01T00:00:00"}]
  }, 
  "2015-01-02T00:00:00" => {
    "PRCP"=>[{"station"=>"GHCND:ZI000067983", "value"=>51, "attributes"=>",,S,", "datatype"=>"PRCP", "date"=>"2015-01-02T00:00:00"}], 
    "TMAX"=>[{"station"=>"GHCND:ZI000067983", "value"=>224, "attributes"=>",,S,", "datatype"=>"TMAX", "date"=>"2015-01-02T00:00:00"}], 
    "TMIN"=>[{"station"=>"GHCND:ZI000067983", "value"=>172, "attributes"=>",,S,", "datatype"=>"TMIN", "date"=>"2015-01-02T00:00:00"}]
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment