knbch
knbch

Reputation: 55

Maintain insertion order for a bash associative array

I'm scripting in Bash.

I have an issue with my associative array, when I put a record in my array like that:

declare -A arr_list_people_name

The way I put text in my associative array in a loop (put text sorted) :

arr_list_people_name[$peopleId]+=$peopleName

The way I read my array:

for KEY in "${!arr_list_people_name[@]}"; do
  # Print the KEY value
  echo "Key: $KEY"
  # Print the VALUE attached to that KEY
  echo "Value: ${arr_list_people_name[$KEY]}"
done

My list is not in the same order compare to the way I recorded it. However, I d like to find the same order than the way I recorded it in my array (sorted by value or key).

Do you have any idea how to manage that ?

Upvotes: 3

Views: 1635

Answers (1)

chepner
chepner

Reputation: 531235

You need to use a second, indexed array to store the keys in the order you add them to arr_list_people_name.

...
arr_list_people_name[$peopleId]+=$peopleName
arr_order+=("$peopleId")
...

for id in "${arr_order[@]}"; do
    echo "Key: $id"
    echo "Value: ${arr_list_people_name[$id]}"
done

Upvotes: 2

Related Questions