With ruby, I am trying to look from the first array key[:nb].value, if there is NOT one similar pair in the second one.
Considerate below arrays contain thousands of elements:
arr1 = [{"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"},{"nb"=>"5jghfj264", "active"=>false, "brand"=>"leg"},{"nb"=>"5qwercv546", "active"=>true, "brand"=>"gem"}]
arr2 = [{"nb"=>"5df54g54df", "active"=>false, "brand"=>"aisle"},{"nb"=>"5jghfj264", "active"=>false, "brand"=>"gem"}]
So far I was thinking something like that :
p (arr1.map(&:nb).find do |nb, val| arr2.map(&:nb)).!Include?(nb && val)
Would you have a suggestion, please?
After finding those who are not present, for those with similar nb.value, how to highlight the difference they have individually? Tks!
CodePudding user response:
My understanding of the question is as follows: "Find the first element h
of arr1
(a hash), such that there is no element g
of arr2
(a hash) for which h["nb"] == g["nb"]
is true".
arr1 = [
{"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"},
{"nb"=>"5jghfj264", "active"=>false, "brand"=>"leg"},
{"nb"=>"5qwercv546", "active"=>true, "brand"=>"gem"}
]
arr2 = [
{"nb"=>"5df54g54df", "active"=>false, "brand"=>"aisle"},
{"nb"=>"5jghfj264", "active"=>false, "brand"=>"gem"}
]
require 'set'
nbs2 = arr2.each_with_object(Set.new) { |h,st| st << h["nb"] }
#=> #<Set: {"5df54g54df", "5jghfj264"}>
arr1.find { |h| !nbs2.include?(h["nb"]) }
#=> {"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"}
One could omit the construction of the set nbs2
and compute
arr1.find { |h| !arr2.include?(h["nb"]) }
but that requires a linear search through arr2
for each element h
of arr1
that is examined. By contrast, determining whether a set contains a specific element is much faster, with the time required to do so almost independent of the size of the set.
CodePudding user response:
Try this
arr1 = [
{"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"},
{"nb"=>"5jghfj264", "active"=>false, "brand"=>"leg"},
{"nb"=>"5qwercv546", "active"=>true, "brand"=>"gem"}
]
arr2 = [
{"nb"=>"5df54g54df", "active"=>false, "brand"=>"aisle"},
{"nb"=>"5jghfj264", "active"=>false, "brand"=>"gem"}
]
# Just create a simple lambda for extracting nb values
extract_nb = ->(h) { h['nb'] }
# Using map just apply array intersection operation
# for finding common key of 'nb'
p arr1.map(&extract_nb) & arr2.map(&extract_nb))
optput
["5df54g54df", "5jghfj264"]