Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array filter using keep_if

Tags:

ruby

I have an array like this:

array = ["john-56", "admin-57", "duke-58", "duke-65", 
         "john-56", "admin-57", "roger-65", "roger-15"]

I want to keep only the elements that are duplicated, in this case I expect to get this result:

["admin-57","admin-57","john-56","john-56"]

I've tried using the keep_if method like this:

array.keep_if { |x,y| x==y }

But it leaves array empty.

like image 514
Supersonic Avatar asked Dec 05 '25 03:12

Supersonic


2 Answers

Maybe not the more efficient, but one line:

array.select { |x| array.count(x) == 2 }.uniq

@edit(thanks to Jounty)

If you have values than can appear more than two times

array.select { |x| array.count(x) > 1 }.uniq
like image 52
epsilon Avatar answered Dec 06 '25 16:12

epsilon


Array#keep_if only passes the current element in the iteration.

You could use:

duplicates = array.keep_if { |x| array.count(x) > 1 }.uniq

Or:

duplicates = array.uniq | array

like image 36
Jon Cairns Avatar answered Dec 06 '25 16:12

Jon Cairns



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!