1

I would like to group an array of arrays of objects by object attribute.

So, if we have

array =[[object1, object2], [object3], [object4, object5, object6]]

and this object has an attribute say "source". Now assume each object has the following source value:

object1> source=source1
object2> source=source2
object3> source=source2
object4> source=source1
object5> source=source1
object6> source=source3

I want to group the arrays that are inside "array" by source attribute.

so I would like to have:

source1 => [object1, object2], [object4, object5, object6]
source2 => [object1, object2] 
source3 => [object4, object5, object6]

for source2, I don't care about array of size 1 so I don't want to add [object3]

Any help?

2
  • can you make this 2D array to single array and then group by.? Commented Jul 16, 2015 at 12:48
  • Do you mean array.flatten.group_by(&:source)? Be more concise please. Commented Jul 16, 2015 at 12:51

1 Answer 1

2

The key thing, which became apparent after your edit, is that you have already grouped your objects, and you want to bucket your groups into potentially more than one bucket based on the objects in each grouping, so this isn't a pure group_by algorithm. Here is one possible solution:

First, create a hash to hold your groups. This sets an empty array as the default value:

sources = Hash.new {|h,k| h[k] = Array.new }

Then reject the ones you don't care about (see Enumerable#reject).

array.reject{|group| group.size == 1}

Finally, iterate through the groups, collecting their sources and adding the group to the appropriate source in the hash. Full example:

sources = Hash.new {|h,k| h[k] = Array.new }

array.reject{|group| group.size == 1}.each do |group|
  group.collect{|group| group.source}.uniq.each do |source|
    sources[source] << group
  end
end
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.