Home > Enterprise >  Couting of array according to hash key in Ruby
Couting of array according to hash key in Ruby

Time:06-17

I have an array

data = [{:user=>1399, :job=>10270}, {:user=>2614, :job=>10270},
        {:user=>3112, :job=>10270}, {:user=>2614, :job=>10271},
        {:user=>1455, :job=>10271}]

Where 1399, 2614, 3112, 1455 are user ids and 10270, 10271 are job ids.

I want to show the number of jobs per user regardless of the job id.

Expected result:

1399 => 1
2614 => 2 # because 2614 has 2 two jobs
3112 => 1
1455 => 1

i need this in an array

CodePudding user response:

You can extract the user ids via map and then let Ruby count the occurrences via tally:

data.map { |h| h[:user] } #=> [1399, 2614, 3112, 2614, 1455]
    .tally                #=> {1399=>1, 2614=>2, 3112=>1, 1455=>1}

CodePudding user response:

First group_by the user key and then count the number of elements in each group:

data = [{:user=>1399, :job=>10270}, {:user=>2614, :job=>10270}, {:user=>3112, :job=>10270}, {:user=>2614, :job=>10271}, {:user=>1455, :job=>10271}]
data.group_by {|e| e[:user]}
  .map{|id, a| [id, a.size]}
  .to_h
# => {1399=>1, 2614=>2, 3112=>1, 1455=>1}
  • Related