遍历哈希数组并组合相似元素
Iterate through an array of hashes and combine similar elements
你好,我有这个数组,例如
array = [
{ingredients: [:t1, :t2], exp: 100, result: :t5},
{ingredients: [:t3, :t4], exp: 200, result: :t10},
{ingredients: [:t1, :t2], exp: 50, result: :t6}
]
我想要一个如下所示的数组:
array = [
{ingredients: [:t1, :t2], exp: 100, results: [:t5, :t6]},
{ingredients: [:t3, :t4], exp: 200, results: [:t10]},
]
所以它应该检查数组中的每个元素,并合并包含相同成分数组的元素的所有结果。
我真的不知道从哪里开始,所以感谢您的帮助。
array = [
{ingredients: [:t1, :t2], exp: 100, result: :t5},
{ingredients: [:t3, :t4], exp: 200, result: :t10},
{ingredients: [:t1, :t2], exp: 50, result: :t6}
]
array.reduce([]) { |memo, e| # will build new array
el = memo.find { |_e| _e[:ingredients] == e[:ingredients] }
if el # already have same ingredients
el[:results] << e[:result] # modify
memo
else
e[:results] = [*e[:result]] # append
e.delete :result
memo << e
end
}
#=> [
# [0] {
# :exp => 100,
# :ingredients => [
# [0] :t1,
# [1] :t2
# ],
# :results => [
# [0] :t5,
# [1] :t6
# ]
# },
# [1] {
# :exp => 200,
# :ingredients => [
# [0] :t3,
# [1] :t4
# ],
# :results => [
# [0] :t10
# ]
# }
#]
希望对您有所帮助。
你好,我有这个数组,例如
array = [
{ingredients: [:t1, :t2], exp: 100, result: :t5},
{ingredients: [:t3, :t4], exp: 200, result: :t10},
{ingredients: [:t1, :t2], exp: 50, result: :t6}
]
我想要一个如下所示的数组:
array = [
{ingredients: [:t1, :t2], exp: 100, results: [:t5, :t6]},
{ingredients: [:t3, :t4], exp: 200, results: [:t10]},
]
所以它应该检查数组中的每个元素,并合并包含相同成分数组的元素的所有结果。
我真的不知道从哪里开始,所以感谢您的帮助。
array = [
{ingredients: [:t1, :t2], exp: 100, result: :t5},
{ingredients: [:t3, :t4], exp: 200, result: :t10},
{ingredients: [:t1, :t2], exp: 50, result: :t6}
]
array.reduce([]) { |memo, e| # will build new array
el = memo.find { |_e| _e[:ingredients] == e[:ingredients] }
if el # already have same ingredients
el[:results] << e[:result] # modify
memo
else
e[:results] = [*e[:result]] # append
e.delete :result
memo << e
end
}
#=> [
# [0] {
# :exp => 100,
# :ingredients => [
# [0] :t1,
# [1] :t2
# ],
# :results => [
# [0] :t5,
# [1] :t6
# ]
# },
# [1] {
# :exp => 200,
# :ingredients => [
# [0] :t3,
# [1] :t4
# ],
# :results => [
# [0] :t10
# ]
# }
#]
希望对您有所帮助。