Ruby -检查一个数组键/值是否存在于另一个数组中

xzv2uavs  于 2023-01-01  发布在  Ruby
关注(0)|答案(2)|浏览(186)

对于ruby,我尝试从第一个数组key [:nb]. value中查找第二个数组中是否有类似的对。
考虑以下数组包含数千个元素:

arr1 = [{"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"},{"nb"=>"5jghfj264", "active"=>false, "brand"=>"leg"},{"nb"=>"5qwercv546", "active"=>true, "brand"=>"gem"}]

arr2 = [{"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"},{"nb"=>"5jghfj264", "active"=>false, "brand"=>"leg"}]

到目前为止,我一直在想这样的事情:
第一个月
你有什么建议吗?

3htmauhk

3htmauhk1#

像这样的东西怎么样?请看下面的评论:

arr1 = [{ 'nb' => '5df54g54df', 'active' => true, 'brand' => 'aisle' }, { 'nb' => '5jghfj264', 'active' => false, 'brand' => 'leg' },
        { 'nb' => '5qwercv546', 'active' => true, 'brand' => 'gem' }]
arr2 = [{ 'nb' => '5df54g54df', 'active' => true, 'brand' => 'aisle' },
        { 'nb' => '5jghfj264', 'active' => false, 'brand' => 'leg' }]

p(
  arr1.select do |h| # Select all objects from arr1, that return true in block:
    arr2.any? { |h2| h['nb'] == h2['nb'] } #Any element from arr2 that contains equal `'nb'` keys.
  end
)

#=> [{"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"}, {"nb"=>"5jghfj264", "active"=>false, "brand"=>"leg"}]
ppcbkaq5

ppcbkaq52#

require 'set'
arr2_nb_vals = arr2.each_with_object(Set.new) do |h,arr2_nb_vals|
  arr2_nb_vals << h["nb"]
end
  #=> #<Set: {"5df54g54df", "5jghfj264"}>
arr1.select { |h| arr2_nb_vals.include?(h["nb"]) }
  #=> [{"nb"=>"5df54g54df", "active"=>true, "brand"=>"aisle"},
  #    {"nb"=>"5jghfj264", "active"=>false, "brand"=>"leg"}]

通过首先将h["nb"]arr2中的h的值收集到一个集合中,arr2_nb_vals.include?(h["nb"])的计算非常快,几乎与arr2_nb_vals.size无关。
这使得当用arr2.include?(h["nb"])替换arr2_nb_vals.include?(h["nb"])时,与O(arr1.size**2)相比,计算复杂度接近O(arr1.size + arr2.size)

相关问题