How do I check an array for duplicates?

RubyArrays

Ruby Problem Overview


I've got an array A. I'd like to check if it contains duplicate values. How would I do so?

Ruby Solutions


Solution 1 - Ruby

Just call uniq on it (which returns a new array without duplicates) and see whether the uniqed array has less elements than the original:

if a.uniq.length == a.length
  puts "a does not contain duplicates"
else
  puts "a does contain duplicates"
end

Note that the objects in the array need to respond to hash and eql? in a meaningful for uniq to work properly.

Solution 2 - Ruby

In order to find the duplicated elements, I use this approach (with Ruby 1.9.3):

array = [1, 2, 1, 3, 5, 4, 5, 5]
=> [1, 2, 1, 3, 5, 4, 5, 5]
dup = array.select{|element| array.count(element) > 1 }
=> [1, 1, 5, 5, 5]
dup.uniq
=> [1, 5]

Solution 3 - Ruby

If you want to return the duplicates, you can do this:

dups = [1,1,1,2,2,3].group_by{|e| e}.keep_if{|_, e| e.length > 1}
# => {1=>[1, 1, 1], 2=>[2, 2]}

If you want just the values:

dups.keys
# => [1, 2]

If you want the number of duplicates:

dups.map{|k, v| {k => v.length}}
# => [{1=>3}, {2=>2}]

Solution 4 - Ruby

Might want to monkeypatch Array if using this more than once:

class Array
  def uniq?
    self.length == self.uniq.length
  end
end

Then:

irb(main):018:0> [1,2].uniq?
=> true
irb(main):019:0> [2,2].uniq?
=> false

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkizitView Question on Stackoverflow
Solution 1 - Rubysepp2kView Answer on Stackoverflow
Solution 2 - RubyjmonteiroView Answer on Stackoverflow
Solution 3 - RubyBenjamin CrouzierView Answer on Stackoverflow
Solution 4 - RubyfakeleftView Answer on Stackoverflow