mickp
mickp

Reputation: 1819

How to get the next element in a sparse array?

I need to get the next element of an array. For contiguous arrays, my code works just fine:

arr=(item{2..5})
value=item3

for ((i=0;i<${#arr[@]};++i)); do
    if [[ ${arr[i]} = "$value" ]] && (( i+1<${#arr[@]} )); then
        echo "${arr[i+1]}"
        break
    fi  
done

I didn't find any definition of how parameter expansion behaves on sparse arrays and this code unfortunately doesn't yield the desired result either:

arr=([3]=item2 [7]=item3 [10]=item4 [1]=item5)

for ((i=0;i<${#arr[@]};++i)); do
    if [[ ${arr[@]:i:1} = "$value" ]]; then
        ...
        ...
    fi
done

How can I do this for sparse arrays (possibly without the need to copy the array as to reindex it) ?

Upvotes: 1

Views: 235

Answers (1)

Cyrus
Cyrus

Reputation: 88999

#!/bin/bash

arr=([3]=item2 [7]=item3 [10]=item4 [1]=item5)
value="item3"
switch="0"

# loop over array's indexes
for i in "${!arr[@]}"; do
  if [[ $switch = "1" ]]; then
    echo "found ${arr[$i]} in element $i"
    switch="0"
    break
  fi

  if [[ ${arr[$i]} = "$value" ]]; then
    echo "found ${arr[$i]} in element $i"
    switch="1"
    continue
  fi
done

Output:

found item3 in element 7
found item4 in element 10

The script does not check whether the end of the array has already been reached.


See: help continue

Upvotes: 2

Related Questions