Reputation: 402
I am looking for an efficient way to give all the duplicate values for an array.
Example:
a = [1,2,2,3,4,7,4,4]
dups(a)
#[[2,2],[4,4,4]]
I've tried using brute force it by doing:
def dups(array)
dups = []
array.uniq.each do |i|
found = array.select{|s| s.eql?(i)}
dups = dups.push found if found.size > 1
end
return dups
end
But it is pretty slow if you small percent of duplicate, since you are looping through the entire array.
Upvotes: 1
Views: 289
Reputation: 402
def dup_group_by(array)
array.group_by(&:itself).filter_map { |_,v| v if v.size > 1 }
end
The key was group_by method which was in the Enumerable module, I was only looking in the Array class.
Upvotes: 3