合并两个数组并删除具有重复的值

时间:2021-06-21 12:19:52

I have two arrays

我有两个数组

a = [1, 2, 3, 4, 5]

b = [2, 4, 6]

I would like to merge the two arrays, then remove the values that is the same with other array. The result should be:

我想合并这两个数组,然后删除与其他数组相同的值。结果应该是:

c = [1, 3, 5, 6]

I've tried subtracting the two array and the result is [1, 3, 5]. I also want to get the values from second array which has not duplicate from the first array..

我试着减去这两个数组,结果是[1,3,5]。我还想从第二个数组中获取值,第二个数组与第一个数组中没有重复。

3 个解决方案

#1


11  

You can do the following!

您可以执行以下操作!

# Merging
c = a + b
 => [1, 2, 3, 4, 5, 2, 4, 6]
# Removing the value of other array
# (a & b) is getting the common element from these two arrays
c - (a & b)
=> [1, 3, 5, 6]

Dmitri's comment is also same though I came up with my idea independently.

迪米特里也发表了同样的看法,尽管我是独立想出这个主意的。

#2


14  

Use Array#uniq.

使用# uniq数组。

a = [1, 3, 5, 6]
b = [2, 3, 4, 5]

c = (a + b).uniq
=> [1, 3, 5, 6, 2, 4]

#3


5  

How about this.

这个怎么样。

(a | b)
=> [1, 2, 3, 4, 5, 6]
(a & b)
=> [2, 4]

(a | b) - (a & b)
[1, 3, 5, 6]

#1


11  

You can do the following!

您可以执行以下操作!

# Merging
c = a + b
 => [1, 2, 3, 4, 5, 2, 4, 6]
# Removing the value of other array
# (a & b) is getting the common element from these two arrays
c - (a & b)
=> [1, 3, 5, 6]

Dmitri's comment is also same though I came up with my idea independently.

迪米特里也发表了同样的看法,尽管我是独立想出这个主意的。

#2


14  

Use Array#uniq.

使用# uniq数组。

a = [1, 3, 5, 6]
b = [2, 3, 4, 5]

c = (a + b).uniq
=> [1, 3, 5, 6, 2, 4]

#3


5  

How about this.

这个怎么样。

(a | b)
=> [1, 2, 3, 4, 5, 6]
(a & b)
=> [2, 4]

(a | b) - (a & b)
[1, 3, 5, 6]