Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count values in a array of hashes

Tags:

arrays

ruby

hash

I have an array of hashes

[ {:name => "bob", :type => "some", :product => "apples"},
  {:name => "ted", :type => "other", :product => "apples"},.... 
  {:name => "Will", :type => "none", :product => "oranges"} ]

and was wondering if there is a simple way to count the number of product's and store the count as well as the value in an array or hash.

I want the result to be something like:

@products =  [{"apples" => 2, "oranges => 1", ...}]
like image 641
user2980830 Avatar asked Dec 12 '22 04:12

user2980830


2 Answers

You can do as

array = [
  {:name => "bob", :type => "some", :product => "apples"},
  {:name => "ted", :type => "other", :product => "apples"},
  {:name => "Will", :type => "none", :product => "oranges"} 
]

array.each_with_object(Hash.new(0)) { |h1, h2| h2[h1[:product]] += 1 }
# => {"apples"=>2, "oranges"=>1}
like image 120
Arup Rakshit Avatar answered Jan 09 '23 11:01

Arup Rakshit


You can use Enumerable#group_by and Enumerable#map

array.group_by{|h| h[:product]}.map{|k,v| [k, v.size]}.to_h
# => {"apples"=>2, "oranges"=>1}
like image 28
Santhosh Avatar answered Jan 09 '23 09:01

Santhosh