开发者

Finding what is common to two arrays

开发者 https://www.devze.com 2023-01-12 05:40 出处:网络
Is there a way to compare two arr开发者_开发技巧ays and show what is common to both of them? array1 = [\"pig\", \"dog\", \"cat\"]

Is there a way to compare two arr开发者_开发技巧ays 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?


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

0

精彩评论

暂无评论...
验证码 换一张
取 消