Finding what is common to two arrays

后端 未结 2 1396
隐瞒了意图╮
隐瞒了意图╮ 2020-12-23 14:31

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\", \"hor         


        
相关标签:
2条回答
  • 2020-12-23 14:53

    You can intersect the arrays using &:

    array1 & array2
    

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

    0 讨论(0)
  • 2020-12-23 14:53

    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 讨论(0)
提交回复
热议问题