title: How to re-sort an indexed array of associative arrays, based on the values in the associative arrays?
body: <p>In my shell code, I have an indexed array, containing the names of associative arrays:</p>
  
  <pre><code>declare -A assoc1=([name]=aaa [age]=20)
  declare -A assoc2=([name]=bbb [age]=40)
  declare -A assoc3=([name]=ccc [age]=25)
  indexed_array=(assoc1 assoc2 assoc3)
  </code></pre>
  
  <p>So, using the above, <code>${indexed_array[@]}</code> equals <code>assoc1 assoc2 assoc3</code>.</p>
  
  <p>I want a <code>sort_array</code> function that can re-sort the values in  <code>indexed_array</code>, so that the associative array with the highest age (assoc2) is listed first or last, like so:</p>
  
  <pre><code>new_indexed_array=( $(echo ${indexed_array[@]} | sort_by 'age' 'desc') )
  </code></pre>
  
  <p>After that I should get re-ordered contents in the new array:</p>
  
  <pre><code>declare -p new_indexed_array
  # gives "assoc2 assoc3 assoc1"
  </code></pre>
  
  <p>I have some boilerplate code to get into the array values, but wasn't able to get any further in sorting the arrays..</p>
  
  <pre class="lang-sh prettyprint-override"><code>function sort_by {
      # for each hash in the given array
      get_stdin # (custom func, sets $STDIN)
      for hash in ${STDIN[@]}
      do
        # get the hash keys
        hash_keys="$(eval "echo \${!$hash[@]}")"
        # for each key
        for hashkey in $hash_keys
        do
          # reset
          return_the_array=false
          # if $hashkey matches the key given
          if [ "$hashkey" = "$1" ];then
            # check the value of this one if highest/lowest
            # (compared to previous ones)
            # and then return if yes/mo (asc/desc)
          fi
          # if $return_the_array = true, then we found the right key and
          # it's higher/lower
          if [ "$return_the_array" = true ];then
            # do stuff
          fi
        done
      done
  }
  </code></pre>