'BASH: sorting an associative array with their keys

So I am quite struggling with arrays in shell scripting, especially dealing with sorting the key values. Here's what I have

declare -A array
Array[0]=(0)
Array[1]=(4)
Array[2]=(6)
Array[3]=(1)

So in each array we have (0,4,6,1), if we sort them to the largest to the smallest, it would be (6,4,1,0). Now, I wonder if I could sort the key of the value, and put them in a new array like this(sort of like ranking them):

newArray[0]=(2) # 2 which was the key for 6
newArray[1]=(1) # 1 which was the key for 4
newArray[2]=(3) # 3 which was the key for 1
newArray[3]=(0) # 0 which was the key for 0

I've tried some solutions but they are so much hard coded and not working for some situations. Any helps would be appreciated.



Solution 1:[1]

  1. Create a tuple of index+value.
  2. Sort over value.
  3. Remove values.
  4. Read into an array.

array=(0 4 6 1)

tmp=$(
   # for every index in the array
   for ((i = 0; i < ${#array[@]}; ++i)); do
       # output the index, space, an array value on every line
       echo "$i ${array[i]}"
   done |
   # sort lines using Key as second column Numeric Reverse
   sort -k2nr |
   # using space as Delimiter, extract first Field from each line
   cut -d' ' -f1
)
# Load tmp into an array separated by newlines.
readarray -t newArray <<<"$tmp"
# output
declare -p newArray

outputs:

declare -a newArray=([0]="2" [1]="1" [2]="3" [3]="0")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1