Home > Net >  How to compare two arrays and get unique values
How to compare two arrays and get unique values

Time:10-27

I have two arrays, I need to compare them and get unique values ​​from the second array only.

Example:

array_first = [1,2,3,4,5,8,9,10,11] # Array for comparison
array_last = [1,2,6,4,7,5,12] # The array from which you want to get values ​​that are not in the other

res: [6,7,12] # The values ​​to get

Is there a way to do this?

CodePudding user response:

Just use Array#-

array_first = [1,2,3,4,5,8,9,10,11]
array_last = [1,2,6,4,7,5,12]

array_last - array_first
#=> [6, 7, 12]

Quote from the docs:

array - other_arraynew_array

Returns a new Array containing only those elements from array that are not found in Array other_array; items are compared using eql? [...]

  •  Tags:  
  • ruby
  • Related