# How to delete existing elements from an array and keep appending new elements afterwards

Below is an example, where I am using two arrays which could be initiated with many elements, for now having "None" as the only element, is there any way to delete existing element/elements and then keep appending new elements when given condition matches otherwise leave the array unaltered.

Looking for a way with minimal coding.

``````array_a=(None)
array_b=(None)
declare -A DICT=([1]="source" [11]="destination" [2]="nowhere")
for index in \${!DICT[@]} ; do
[[ \${index} =~ 1 ]] && array_a+=("\${DICT[\${index}]}")
[[ \${index} =~ 50 ]] && array_b+=("\${DICT[\${index}]}")
done
echo \${array_a[@]}
echo \${array_b[@]}
``````

Output:

``````None destination source
None
``````

Expected Output:

``````destination source
None
``````

I am having a dumb solution for this

``````array_a=(None)
array_b=(None)
declare -A DICT=([1]="source" [11]="destination" [2]="nowhere")
a=0
b=0
for index in \${!DICT[@]} ; do
if [[ \${index} =~ 1 ]] ; then if [[ \${a} -eq 0 ]] ; then ((a++)) ; unset array_a ; fi ; array_a+=("\${DICT[\${index}]}") ; fi
if [[ \${index} =~ 50 ]]; then if [[ \${b} -eq 0 ]] ; then ((b++)) ;  unset array_b ; fi ; array_b+=("\${DICT[\${index}]}") ; fi
done
echo \${array_a[@]}
echo \${array_b[@]}
``````

Output:

``````destination source
None
``````

Use this:

``````ini_array_a=(None xyz)
ini_array_b=()
array_a=()
array_b=()
[...]
array_a=(\${array_a[@]:-\${ini_array_a[@]}})
array_b=(\${array_b[@]:-\${ini_array_b[@]}})
echo \${array_a[@]:-None}
echo \${array_b[@]:-None}
``````

Where `\$ini_array_a` and `\$ini_array_b` are the already initialized arrays. We define two new arrays with no value inside. Then do your processing. For echoing the arrays, use Parameter Expansion. The arrays `\$array_a` and `array_b` are those to print in the end (this is to address your comment).

``````\${parameter:-word}

If parameter is unset or null, the expansion of word is substituted.
Otherwise, the value of parameter is substituted.
``````
• Alternately, after the loop, `"\${array_a[0]:=None}"` to assign a default value.
– muru
Aug 31, 2018 at 7:45
• It would require to have a new loop through all the arrays, can it be adjusted in the same loop, however question is assuming there are some existing elements in arrays. Aug 31, 2018 at 7:50
• @Bharat "some existing elements"? More than one? Please clarify the question with what you actually have and what parts of the code you can modify.
– muru
Aug 31, 2018 at 7:58
• @muru Yes, I mean right now I am only considering None as the only element in array, but there could be many in it, eg. ( None xyz ...) so what I want if condition matches unset the array and append the elements, if it doesn't match just leave all the elements which were there initially i.e None xyz ... Aug 31, 2018 at 8:01
• @chaos Assumption is to have initialized arrays in the question. Aug 31, 2018 at 8:17