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?
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.
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.
You can intersect the arrays using &
:
array1 & array2
This will return ["pig", "dog", "cat"]
.
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
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