Home > database >  Alphabetically sorting an array within an array in Ruby?
Alphabetically sorting an array within an array in Ruby?

Time:09-02

Method input: ["eat","tea","tan","ate","nat","bat"]

I have grouped each of the anagrams into their own array within an array through this method and then sorted the array by group size:

def group_anagrams(a)
    a.group_by { |stringElement| stringElement.chars.sort }.values.sort_by(&:size)
end

I am struggling to figure out how to alphabetically sort the resulting arrays within the array here because as you can see nat should come before tan in the middle element of the array:

[["bat"], ["tan", "nat"], ["eat", "tea", "ate"]]

Updating with final solution:

def group_anagrams(a)
    a.group_by { |stringElement| stringElement.chars.sort }.values.map(&:sort).sort_by(&:size)
end

CodePudding user response:

You need to map this array and sort (map(&:sort))

def group_anagrams(ary)
  ary.group_by { |s| s.chars.sort }.values.map(&:sort)
end
ary = ["eat", "tea", "tan", "ate", "nat", "bat"]
group_anagrams(ary)
# => [["ate", "eat", "tea"], ["nat", "tan"], ["bat"]]
  • Related