Reputation: 5521
I'd like to reorder an array of arrays. By default, the array is sorted by the English keys:
english_sorted_terms = [
[
"A1_english", {"domains"=>[], "en"=>{"name"=>"A_english", "def"=>"A"}, "de"=>{"name"=>"Z_german", "def"=>"..." }}
],
[
"Z1_english", {"domains"=>[], "en"=>{"name"=>"Z_english", "def"=>"Z"}, "de"=>{"name"=>"A_german", "def"=>"..."}}
]
]
After sorting, 'Z1_english' should be the first element because it contains the name 'A_german'.
My other attempts do correct the 'de' sub-key but I cannot reinsert the right parent key or the key but the sorting isn't right
english_sorted_terms
.map { |term| term[1] }
.sort_by { |key| key["de"]['name'] }
english_sorted_terms
.map { |term| [term[1]].sort_by! { |key| key["de"]['name'] }.unshift term[0] }
.sort_by! { |key| key["de"]['name'] }
is working but it removes the first array element.
Upvotes: 0
Views: 61
Reputation: 111
Ruby sorting works by comparing elements and you can define the comparison criteria yourself. In this example you compare with original array item's second element's ['de']['name']. For example:
english_sorted_terms.sort { |a, b| a.second['de']['name'] <=> b.second['de']['name'] }
See https://apidock.com/ruby/Array/sort.
Upvotes: 2