简体   繁体   English

如何获得数组中的唯一元素并折叠在一起?

[英]How to get those unique element in an array and collapse together?

animals = [
  {type: "dog", a: 2},
  {type: "dog", b: 7},
  {type: "dog", c: 2},
  {type: "cat", d: 3},
  {type: "cat", e: 4},
  {type: "cat", f: 0},
  {type: "rabbit", g: 0},
  {type: "rabbit", h: 1}
]

How to convert into 如何转换成

animals = [
  {type:"dog", a:2, b:7, c:2},
  {type:"cat", d:3, e:4, f:0},
  {type:"rabbit", g:0, h:1}
]

I don't know how to do it in a good way. 我不知道该怎么做。 Using each and using if else statements to extract is too clumsy. 使用each语句和使用if else语句提取都太笨拙。 Any ideas? 有任何想法吗?

I'd do as below : 我会做如下:

animals = [
  {type: "dog", a: 2},
  {type: "dog", b: 7},
  {type: "dog", c: 2},
  {type: "cat", d: 3},
  {type: "cat", e: 4},
  {type: "cat", f: 0},
  {type: "rabbit", g: 0},
  {type: "rabbit", h: 1}
]

array_of_merged_hash = animals.group_by do |inner_hash|
  inner_hash[:type]
end.map { |_,v| v.reduce(:merge) }

array_of_merged_hash
# => [{:type=>"dog", :a=>2, :b=>7, :c=>2},
#     {:type=>"cat", :d=>3, :e=>4, :f=>0},
#     {:type=>"rabbit", :g=>0, :h=>1}]

methods are : group_by , reduce and map . 方法是: group_byreducemap

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM