开发者

How do I check an array for duplicates? [duplicate]

This question already has answers here: How to find and return a duplicate value in array (23 answers) 开发者_JAVA技巧 Closed 8 years ago.

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


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.


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]


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}]


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜