Created
March 6, 2015 21:37
-
-
Save francirp/981bd60831e335d5836d to your computer and use it in GitHub Desktop.
Group an array two levels deep
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Components::Extensions::GroupBy | |
def group_by_two_levels(args = {}) | |
array, first, second = [args[:array], args[:first], args[:second]] | |
hash = array.group_by do |obj| | |
obj.respond_to?(first) ? obj.send(first) : obj[first] | |
end | |
hash.each do |first, obj_array| | |
hash[first] = obj_array.group_by do |obj| | |
obj.respond_to?(second) ? obj.send(second) : obj[second] | |
end | |
end | |
hash | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example: