PedroNG
PedroNG

Reputation: 31

Loop through keys of an array, in order

is that easily possible?

I have the next code:

for each_key in "${!myArray[@]}"
    do
        echo $each_key" : "${myArray[$each_key]}
    done

sure it works flawesly, but items do not show in order

I try with

IFS=$'\n' orderedMyArray=($(sort <<< "${myArray[@]}"))
declare -p orderedMyArray

but is giving me values and not keys

Upvotes: 0

Views: 89

Answers (2)

Paul Hodges
Paul Hodges

Reputation: 15293

If you mean something other than sorting the keys themselves in alphabetic order, you could try a parallel array.

$: order=( peach pear lemon lime ) # declare the order you want
$: declare -A data=( [peach]=pickled [pear]=salad [lemon]=drop [lime]=twist )
$: for k in "${order[@]}"; do echo "$k: ${data[$k]}"; done
peach: pickled
pear: salad
lemon: drop
lime: twist

Upvotes: 0

KamilCuk
KamilCuk

Reputation: 141145

it works flawesly, but items do not show in order

Sure and ordering them on keys is trivial - just actually sort on the keys.

for each_key in "${!myArray[@]}"; do
    echo "$each_key : ${myArray[$each_key]}" # remember to quote variable expansions!
done | sort

You could sort keys before passing them to for:

for each_key in "$(printf "%s\n" "${!myArray[@]}" | sort)"; do
# or funnier:
for each_key in $(IFS=$'\n'; sort <<<"${!myArray[*]}"); do
# or I think I would do a while read:
keys=$(IFS=$'\n'; sort <<<"${!myArray[*]}")
while IFS= read -r each_key; do ...; done <<<"$keys"

Upvotes: 1

Related Questions