Home > other >  logic to verify if the element is present in array from list of object
logic to verify if the element is present in array from list of object

Time:07-14

I have an 2 array with some String values. I wanted to check if one array's all value are part of another arrays. Is there any defined method available to check it or how to implement in optimised way.

Ex:

arr1 = ['abc', 'def']

arr2 = ['abc', 'def', 'ghi', 'jkl']

if values of array 1 is present in array 2 then only control should move ahead in code else it should return.

CodePudding user response:

You have a few ways of doing that. Perhaps the easiest way is to use the Set class:

a = ["1","2","5"]
b = ["2", "5"]

s1 = Set.new(a)
s2 = Set.new(b)

s2.subset?(s1) # => true
s1.subset?(s2) # => false                   

c = ["5", "2"]
s3 = Set.new(c)
s3.subset?(s1) # true

If you decide to use the intesection (&) method, you need to be aware that the order matters:

a = ["1","2","5"]
b = ["2", "5"]
c = ["5", "2"]

a & b # => ["2", "5"]
a & c # => ["2", "5"]

b & a # => ["2", "5"]
c & a # => ["5", "2"]

Then, you can take advantage of ==:

(a & b) == b # => true
(a & c) == c # => false
(b & a) == b # => true
(c & a) == c # => true

You can also use all?:

a = ["1","2","5"]
b = ["2", "5"]

a.all? {|e| b.include?(e) } # => false
b.all? {|e| a.include?(e) } # => true

CodePudding user response:

(arr1 & arr2).size == arr2.size

or

 (arr1 & arr2) == arr2
  • Related