I have the following Array = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"]
How do I produce a count for each identical element?
Where: "Jason" = 2, "Judah" = 3, "Allison" = 1, "Teresa" = 1, "Michelle" = 1?
or produce a hash Where:
Where: hash = { "Jason" => 2, "Judah" => 3, "Allison" => 1, "Teresa" => 1, "Michelle" => 1 }
To count the duplicates in an array:Declare an empty object variable that will store the count for each value. Use the forEach() method to iterate over the array. On each iteration, increment the count for the value by 1 or initialize it to 1 .
Ruby | Array count() operation Array#count() : count() is a Array class method which returns the number of elements in the array. It can also find the total number of a particular element in the array. Syntax: Array. count() Parameter: obj - specific element to found Return: removes all the nil values from the array.
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.
As of ruby v2.7.0 (released December 2019), the core language now includes Enumerable#tally
- a new method, designed specifically for this problem:
names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"] names.tally #=> {"Jason"=>2, "Teresa"=>1, "Judah"=>3, "Michelle"=>1, "Allison"=>1}
The following code was not possible in standard ruby when this question was first asked (February 2011), as it uses:
Object#itself
, which was added to Ruby v2.2.0 (released December 2014).Hash#transform_values
, which was added to Ruby v2.4.0 (released December 2016).These modern additions to Ruby enable the following implementation:
names = ["Jason", "Jason", "Teresa", "Judah", "Michelle", "Judah", "Judah", "Allison"] names.group_by(&:itself).transform_values(&:count) #=> {"Jason"=>2, "Teresa"=>1, "Judah"=>3, "Michelle"=>1, "Allison"=>1}
If using an older ruby version, without access to the above mentioned Hash#transform_values
method, you could instead use Array#to_h
, which was added to Ruby v2.1.0 (released December 2013):
names.group_by(&:itself).map { |k,v| [k, v.length] }.to_h #=> {"Jason"=>2, "Teresa"=>1, "Judah"=>3, "Michelle"=>1, "Allison"=>1}
For even older ruby versions (<= 2.1
), there are several ways to solve this, but (in my opinion) there is no clear-cut "best" way. See the other answers to this post.
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