A
A
Andrey2018-02-05 14:04:44
ruby
Andrey, 2018-02-05 14:04:44

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"]}
]

You need to group hashes by key, like:
[
  {:car=>},
  {:country=>},
  {:city=>["Moscow", "Tokyo", "Amsterdam"]}
]

those. concatenate arrays with the same key.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-02-05
@andreychumak

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 question

Ask a Question

731 491 924 answers to any question