Reputation: 33552
I have two Arrays with hashes that looks like below
array_1 = [{"id": "1", "value": "Option_A", default_weight: "50"}, {"id": "2", "value": "Option_B", default_weight: "75"}]
array_2 = [{"id": "2", "value": "Option_B", custom_weight: "35"}]
Now I'm trying build an array which will contain only weights based on the following condition
Pick the default_weight
of the object from array_1
if that doesn't exist in array_2
. If it exists in array_2
, pick custom_weight
The expected output will be [50.0, 35.0]
My failed attempt:
new_array = []
array_1.each do |array_1_item|
array_2.map {|array_2_item| array_1_item["value"] == array_2_item["value"] ? new_array << array_2_item["custom_weight"].to_f : new_array << array_1_item[:default_weight].to_f}
end
I get [50.0, 50.0, 35.0, 75.0]
Any help is much appreciated, TIA
Upvotes: 0
Views: 54
Reputation: 6899
Try turning array_2
into a hash first:
custom_weights = {}
array_2.each { |item| custom_weights[item[:value]] = item[:custom_weight] }
Then you can do:
array_1.map { |item| (custom_weights[item[:value]] || item[:default_weight]).to_f }
=> [50.0, 35.0]
Upvotes: 1