I have 2 arrays:
@array1 = [a,b,c,d,e] @array2 = [d,e,f,g,h]
I want to compare the two arrays to find matches (d,e) and count the number of matches found (2)?
<% if @array2.include?(@array1) %> # yes, but how to count instances? <% else %> no matches found... <% end %>
Thanks in advance~
Arrays can be equal if they have the same number of elements and if each element is equal to the corresponding element in the array. To compare arrays in order to find if they are equal or not, we have to use the == operator.
Using Arrays. equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method. Using Arrays. deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
Programmers who wish to compare the contents of two arrays must use the static two-argument Arrays. equals() method. This method considers two arrays equivalent if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equivalent, according to Object.
You can do this with array intersection:
@array1 = ['a', 'b', 'c', 'd', 'e'] @array2 = ['d', 'e', 'f', 'g', 'h'] @intersection = @array1 & @array2
@intersection should now be ['d', 'e']. You can then do the following:
<% if [email protected]? %> <%= @intersection.size %> Matches Found. <% else %> No Matches Found. <% end %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With