What’s the best way to change a big array into multiple sub arrays based on the property of the objects in the original array? For example I have an array of objects(all objects have the same properties):
array = [
{:name => "Jim", :amount => "20"},
{:name => "Jim", :amount => "40"},
{:name => "Jim", :amount => "30"},
{:name => "Eddie", :amount => "7"},
{:name => "Eddie", :amount => "12"},
{:name => "Pony", :amount => "330"},
{:name => "Pony", :amount => "220"},
{:name => "Pony", :amount => "50"}
]
Note that all objects with the same name property are consecutive in the array. Now I want to group the objects into sub arrays based on the name property. What I need is:
result = [
[
{:name => "Jim", :amount => "20"},
{:name => "Jim", :amount => "40"},
{:name => "Jim", :amount => "30"}
],
[
{:name => "Eddie", :amount => "7"},
{:name => "Eddie", :amount => "12"}
],
[
{:name => "Pony", :amount => "330"},
{:name => "Pony", :amount => "220"},
{:name => "Pony", :amount => "50"}
]
]
What’s the best way to do this?
Thanks.
Use
group_byfor the heavy lifting and thenmapto pull out what you want:For example:
You could also skip the
mapand go straight toHash#values:Thanks go to KandadaBoggu for pointing out this oversight.