Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare Two Arrays and Remove Unique Values [duplicate]

I have two arrays

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

some_list = [2, 6, 4]

I would like to compare the two arrays, then find the duplicates, and form it into a new array. The trick is to keep the array in the order provided in the ordered array.

new_array = [2, 4] # Result should be this

I've thought of one way to do it, however I think the performance can be improved.

ordered.each do |value1|
  some_list.include? value1 
    new_array << value1
  end
end

Is there any way I can improve this?

Benchmark results

                   user     system      total        real
  using &        0.210000   0.000000   0.210000 (  0.212070)
  using select   0.220000   0.000000   0.220000 (  0.218889)
like image 494
thank_you Avatar asked Oct 04 '13 20:10

thank_you


3 Answers

Try this new_arry = order­ed & some_­list

like image 195
Raghu Avatar answered Sep 30 '22 07:09

Raghu


It can also be done in following way:

uniques = ordered - some_list
duplicates = ordered - uniques

Order will be preserved.

Refer: http://ruby-doc.org/core-2.0.0/Array.html#method-i-2D

like image 36
Munish Avatar answered Sep 30 '22 07:09

Munish


ordered.select{|i| some_list.include?(i)}

Edit:

Not really sure if select is optimised for performance, but it is provided as shorter and clear alternative to the code provided by the OP.

A quick benchmark gave this results: Edit: adding the accepted answer alternative.

           user     system      total        real
  each  0.000000   0.000000   0.000000 (  0.000005)
select  0.000000   0.000000   0.000000 (  0.000004)
     &  0.000000   0.000000   0.000000 (  0.000005)
like image 37
Christian Avatar answered Sep 30 '22 09:09

Christian