Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - Merge two arrays and remove values that have duplicate

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..

like image 428
user3204760 Avatar asked Nov 23 '15 01:11

user3204760


People also ask

How do I merge two arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).

Does array concat remove duplicates?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates.


2 Answers

Use Array#uniq.

a = [1, 3, 5, 6] b = [2, 3, 4, 5]  c = (a + b).uniq => [1, 3, 5, 6, 2, 4] 
like image 84
EJAg Avatar answered Sep 18 '22 14:09

EJAg


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.

like image 22
Rubyrider Avatar answered Sep 18 '22 14:09

Rubyrider