Count duplicate elements in ruby array (Ruby 1.9+)
Returns a hash with the element value as a key and its count
a = [1, 2, 3, 2, 5, 6, 7, 5, 5]
a.each_with_object(Hash.new(0)) { |o, h| h[o] += 1 }
# => {1=>1, 2=>2, 3=>1, 5=>3, 6=>1, 7=>1}
In order to filter the result with a certain threshold, add ...
.map{|k,v| k if v >= 2}.compact
# => [2, 5]
Written by Frank Wambutt
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Ruby
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#