1

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.

2
  • 2
    Not exactly the desired output, but pretty efficient: a.tally.select{|k,v| v>1 } Commented May 18, 2022 at 21:32
  • 2
    @steenslag simple enough to modify though a.tally.filter_map {|k,v| [k] * v if v > 1} Commented May 18, 2022 at 22:04

1 Answer 1

3
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.

Sign up to request clarification or add additional context in comments.

4 Comments

@engineersmnky thanks! - I copy my old method and didn't clean it up; I updated it with your suggestions
Consider array.group_by(&:itself).filter_map { |_,v| v if v.size > 1 } #=> [[2, 2], [4, 4, 4]]. @engineersmnky, I expected that whatever you suggested in would include Enumerable#filter_map.
@CarySwoveland agreed just wasn't trying to disagree with a viable solution from a new comer. See my comment under the original post 😀
@engineersmnky, that comment prompted mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.