我想按年份对此进行分组:
[{"_id"=>{"year"=>2013, "month"=>8}, "count"=>69605},
{"_id"=>{"year"=>2013, "month"=>7}, "count"=>60620},
{"_id"=>{"year"=>2013, "month"=>12}, "count"=>56026},
{"_id"=>{"year"=>2014, "month"=>5}, "count"=>55067},
{"_id"=>{"year"=>2014, "month"=>4}, "count"=>51313},
{"_id"=>{"year"=>2013, "month"=>11}, "count"=>48044},
{"_id"=>{"year"=>2014, "month"=>8}, "count"=>43802},
{"_id"=>{"year"=>2014, "month"=>1}, "count"=>40428},
{"_id"=>{"year"=>2014, "month"=>3}, "count"=>39564},
{"_id"=>{"year"=>2013, "month"=>9}, "count"=>35682},
{"_id"=>{"year"=>2013, "month"=>10}, "count"=>34073},
{"_id"=>{"year"=>2014, "month"=>2}, "count"=>32774},
{"_id"=>{"year"=>2014, "month"=>6}, "count"=>30772},
{"_id"=>{"year"=>2014, "month"=>9}, "count"=>17347},
{"_id"=>{"year"=>2014, "month"=>7}, "count"=>5319},
{"_id"=>{"year"=>2013, "month"=>6}, "count"=>4468},
{"_id"=>{"year"=>2013, "month"=>5}, "count"=>2978},
{"_id"=>{"year"=>2013, "month"=>4}, "count"=>2498},
{"_id"=>{"year"=>2013, "month"=>3}, "count"=>360},
{"_id"=>{"year"=>2013, "month"=>1}, "count"=>112},
{"_id"=>{"year"=>2012, "month"=>12}, "count"=>88},
{"_id"=>{"year"=>2013, "month"=>2}, "count"=>28},
{"_id"=>{"year"=>2015, "month"=>11}, "count"=>1}]
有人可以帮助我吗?
答案 0 :(得分:3)
试试这个
Your_Array.group_by{|a| a["_id"]["year"]}
答案 1 :(得分:1)
您的问题已解决,请查看以下解决方案
Your_array.group_by { |d| d['_id']['year'] }
答案 2 :(得分:0)
Enumerable#reduce
来救援。假设数据存储在数据变量中:
data.reduce({}) { |memo, item|
(memo[item['_id']['year']] ||= []) << item;
memo
}
# => {
# 2012 => [
# [0] {
# "_id" => {
# "month" => 12,
# "year" => 2012
# },
# "count" => 88
# }
# ],
# 2013 => [
# [ 0] {
# ...
可能就是你要找的东西。是否要生成重组数据,只需修改被调用者。
答案 3 :(得分:0)
我想这对你有用:
array.group_by{|a| a["_id"]["year"]}.values
答案 4 :(得分:0)
使用Enumerable#group_by
。
array.group_by { |record| record['_id']['year'] }
#=> {2013=>
# [{"_id"=>{"year"=>2013, "month"=>8}, "count"=>69605},
# ...
# {"_id"=>{"year"=>2013, "month"=>2}, "count"=>28}],
# 2014=>
# [{"_id"=>{"year"=>2014, "month"=>5}, "count"=>55067},
# ...
# {"_id"=>{"year"=>2014, "month"=>7}, "count"=>5319}],
# 2012=>[{"_id"=>{"year"=>2012, "month"=>12}, "count"=>88}],
# 2015=>[{"_id"=>{"year"=>2015, "month"=>11}, "count"=>1}]}
答案 5 :(得分:0)
使用Enumerable#group_by
grouped_array = array.group_by {|record| record["_id"]["year"]}
使用Enumerable#sort_by
对记录进行排序
sorted_array = grouped_array.sort_by{|year, records| year}
formated_hash = sorted_array.to_h
这将按年份的升序值排序。如果您想按降序排序,请使用Array.reverse
desc_sorted_array = sorted_array.reverse
formated_hash = desc_sorted_array.to_h