Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding what is common to two arrays

Tags:

ruby

Is there a way to compare two arrays and show what is common to both of them?

array1 = ["pig", "dog", "cat"] array2 = ["dog", "cat", "pig", "horse"] 

What do I type to show that ["pig", "dog", "cat"] are common between these two arrays?

like image 433
miles Avatar asked Aug 20 '10 17:08

miles


People also ask

How can you tell if two arrays are similar?

The Arrays. equals() method checks the equality of the two arrays in terms of size, data, and order of elements. This method will accept the two arrays which need to be compared, and it returns the boolean result true if both the arrays are equal and false if the arrays are not equal.

How do you find the uncommon element in two arrays?

const arr1 = [12, 54, 2, 4, 6, 34, 3]; const arr2 = [54, 2, 5, 12, 4, 1, 3, 34]; We are required to write a JavaScript function that takes in two such arrays and returns the element from arrays that are not common to both.


2 Answers

You can intersect the arrays using &:

array1 & array2 

This will return ["pig", "dog", "cat"].

like image 144
Raoul Duke Avatar answered Sep 28 '22 23:09

Raoul Duke


Set Intersection. Returns a new array containing elements common to the two arrays, with no duplicates, like:

["pig", "dog", "bird"] & ["dog", "cat", "pig", "horse", "horse"] # => ["pig", "dog"] 

You can also read a blog post about Array coherences

like image 40
Christian Rolle Avatar answered Sep 28 '22 21:09

Christian Rolle