Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group by count in array without using loop

Tags:

ruby

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 
like image 438
Mr. Black Avatar asked Mar 29 '11 09:03

Mr. Black


People also ask

How do you count the number of occurrences of an element in a array in Javascript?

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 .

How can you get the number of items contained in an array Ruby?

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.

How do you split an array in Ruby?

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.

How do you use reduce in Ruby?

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.


2 Answers

x = arr.inject(Hash.new(0)) { |h, e| h[e] += 1 ; h } 
like image 183
Michael Kohl Avatar answered Sep 22 '22 08:09

Michael Kohl


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,

  • When the starting element is a mutable object such as an 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

like image 35
sawa Avatar answered Sep 19 '22 08:09

sawa