How to find an item in array which has the most occurrences [duplicate]

First build a hash mapping each value in the array to its frequency…

arr = [1, 1, 1, 2, 3]

freq = arr.inject(Hash.new(0)) { |h,v| h[v] += 1; h }
#=> {1=>3, 2=>1, 3=>1}

… then use the frequency table to find the element with the highest frequency:

arr.max_by { |v| freq[v] }
#=> 1

Leave a Comment