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)
Try this new_arry = ordered & some_list
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With