Bash – How to sort an associative array and retain the keys

arraybashsort

I have an array with filenames as keys and a numerical value as values.

MYARRAY[00001.jpg] = 31
MYARRAY[00002.jpg] = 200
MYARRAY[00003.jpg] = 98

I need to sort them so they are ordered by value.
Which I am doing with

IFS=$'\n' SORTED=($(sort <<<"${MYARRAY[*]}"))

However I lose the keys and just have numerical ones now.

Desired output would be

00001.jpg:31
00003.jpg:98
00002.jpg:200

How can I retain the keys in such a sort?

Best Answer

Assuming your keys don't contain colons or newlines and your values don't contain newlines:

for key in "${!MYARRAY[@]}"; do
  printf '%s:%s\n' "$key" "${MYARRAY[$key]}"
done | sort -t : -k 2n

If you need to arrange the key in the order given by the values, read back the output:

IFS=$'\n'; set -f
sorted_keys=($(
    for key in "${!MYARRAY[@]}"; do
      printf '%s:%s\n' "$key" "${MYARRAY[$key]}"
    done | sort -t : -k 2n | sed 's/:.*//'))
unset IFS; set +f
Related Question