arr = [1,2,1,3,5,2,4]
How can I count the array by group value with sorting? I need the following output:
x[1] = 2 x[2] = 2 x[3] = 1 x[4] = 1 x[5] = 1
To count the occurrences of each element in an array:Declare a variable that stores an empty object. Use the for...of loop to iterate over the array. On each iteration, increment the count for the current element if it exists or initialize the count 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.
split is a String class method in Ruby which is used to split the given string into an array of substrings based on a pattern specified. Here the pattern can be a Regular Expression or a string. If pattern is a Regular Expression or a string, str is divided where the pattern matches.
reduce(0) sets the initial value. After that, we have two parameters in the method (|sum, num|). The first parameter, which we call 'sum' here is the total that will eventually be returned. The second parameter, which we call 'num' is the current number as we iterate through the array.
x = arr.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h }
Only available under ruby 1.9
Basically the same as Michael's answer, but a slightly shorter way:
x = arr.each_with_object(Hash.new(0)) {|e, h| h[e] += 1}
In similar situations,
Array
, Hash
, String
, you can use each_with_object
, as in the case above.When the starting element is an immutable object such as Numeric
, you have to use inject
as below.
sum = (1..10).inject(0) {|sum, n| sum + n} # => 55
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