Answer the question
In order to leave comments, you need to log in
How to group an array of hashes by key?
There is an array consisting of hashes:
[
{:car=>["BMW", "Mersedes", "Audi"]},
{:car=>["Renault", "Ferrari", "Nissan"]},
{:car=>["VW"]},
{:country=>["Russia", "Japan", "USA"]},
{:country=>["China", "Nigeria", "Egypt"]},
{:city=>["Moscow", "Tokyo", "Amsterdam"]}
]
[
{:car=>},
{:country=>},
{:city=>["Moscow", "Tokyo", "Amsterdam"]}
]
Answer the question
In order to leave comments, you need to log in
a = [
{:car=>["BMW", "Mersedes", "Audi"]},
{:car=>["Renault", "Ferrari", "Nissan"]},
{:car=>["VW"]},
{:country=>["Russia", "Japan", "USA"]},
{:country=>["China", "Nigeria", "Egypt"]},
{:city=>["Moscow", "Tokyo", "Amsterdam"]}
]
b = a.group_by{|n| n.keys[0]}.map{|k, n| {k => n.map{|m| m[k]}}}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question