Home > Back-end >  Sort array of arrays by hash key in value and reinsert key
Sort array of arrays by hash key in value and reinsert key

Time:06-24

I'd like to reorder an array of arrays. By default, the array is sorted by the English keys.

My input

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"=>"..."}}
  ]
]

'Z1_english' must be the first element after sorting because it contains the name 'A_german'. .sort_by! { |key| key["de"]['name'] } is working but it removes the first array element.

My attempts so far

This code corrects the 'de' sub-key but I cannot reinsert the right parent key:

english_sorted_terms
  .map { |term| term[1] } 
  .sort_by { |key| key["de"]['name'] }

This code reinserts the key but the sorting isn't right:

english_sorted_terms
  .map { |term| [term[1]].sort_by! { |key| key["de"]['name'] }.unshift term[0] } 

CodePudding user response:

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.

  • Related