找到两个数组的共同点

时间:2021-01-03 12:47:54

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?

我输入什么来表示["pig", "dog", "cat"]在这两个数组中是常见的?

2 个解决方案

#1


113  

You can intersect the arrays using &:

您可以使用&:

array1 & array2

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

这将返回["猪","狗","猫"]。

#2


2  

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

你也可以读一篇关于数组相干的博文

#1


113  

You can intersect the arrays using &:

您可以使用&:

array1 & array2

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

这将返回["猪","狗","猫"]。

#2


2  

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

你也可以读一篇关于数组相干的博文