I have an array with some elements. How can I get the number of occurrences of each element in the array?
For example, given:
a = ['cat', 'dog', 'fish', 'fish']
The result should be:
a2 #=> {'cat' => 1, 'dog' => 1, 'fish' => 2}
How can I do that?
By using hashmap's key. In Java, the simplest way to get unique elements from the array is by putting all elements of the array into hashmap's key and then print the keySet(). The hashmap contains only unique keys, so it will automatically remove that duplicate element from the hashmap keySet.
The first() is an inbuilt method in Ruby returns an array of first X elements. If X is not mentioned, it returns the first element only. Parameters: The function accepts X which is the number of elements from the beginning. Return Value: It returns an array of first X elements.
The . last property of an array in Ruby returns the last element of the array.
You can use Enumerable#group_by
to do this:
res = Hash[a.group_by {|x| x}.map {|k,v| [k,v.count]}] #=> {"cat"=>1, "dog"=>1, "fish"=>2}
a2 = a.reduce(Hash.new(0)) { |a, b| a[b] += 1; a } #=> {"cat"=>1, "fish"=>2, "dog"=>1}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With