How to count duplicates in Ruby Arrays

Viewed 30658

How do you count duplicates in a ruby array?

For example, if my array had three a's, how could I count that

17 Answers

To count instances of a single element use inject

array.inject(0){|count,elem| elem == value ? count+1 : count}
arr = [1, 2, "a", "a", 4, "a", 2, 1]

arr.group_by(&:itself).transform_values(&:size)
#=> {1=>2, 2=>2, "a"=>3, 4=>1}

Ruby >= 2.7 solution here:

A new method .tally has been added.

Tallies the collection, i.e., counts the occurrences of each element. Returns a hash with the elements of the collection as keys and the corresponding counts as values.

So now, you will be able to do:

["a", "b", "c", "b"].tally  #=> {"a"=>1, "b"=>2, "c"=>1}

Ruby code to get the repeated elements in the array:

numbers = [1,2,3,1,2,0,8,9,0,1,2,3]
similar =  numbers.each_with_object([]) do |n, dups|
    dups << n if seen.include?(n)
    seen << n 
end
print "similar --> ", similar

Another way to do it is to use each_with_object:

a = [ 1, 2, 3, 3, 4, 3]

hash = a.each_with_object({}) {|v, h|
  h[v] ||= 0
  h[v] += 1
}

# hash = { 3=>3, 2=>1, 1=>1, 4=>1 } 

This way, calling a non-existing key such as hash[5] will return nil instead of 0 with Kim's solution.

Related