Games
Problems
Go Pro!

# Removing an Array Element

Reference > Science > Technology > Beginner Programming Tips

Suppose you have an array of 10 Integers, and you want to remove one of those elements from your array. How do you do it? The code snippet below shows a subroutine which does the job. Take a look at it, then we'll talk through it.

Dim MyArray(9) As Integer

'Remove element from the array
Sub RemoveElement(Index As Integer)
Dim I As Integer
For I = Index To UBound(MyArray) - 1
MyArray(I) = MyArray(I + 1)
Next I
ReDim Preserve MyArray(UBound(MyArray) - 1)
End Sub

What is happening here? Simple. Index is the variable indicating which element you want to remove from the array. The For-Next loop walks through the array, starting at that point, and going to the end of the array, replacing each array element with the following array element. This has the effect of removing the unwanted element (overwriting it with another element) and sliding everything else up one index in the array.

Notice that the For-Next loop stops one element short of the end of the array. There is a good reason for this; if we went all the way to the end, including the last element, the following line:

MyArray(I) = MyArray(I + 1)

would have produced an error, since (I + 1) would be an invalid array index.

Of course, when you are done, your array has an unneeded index at the end, so you can use the "ReDim" command to knock out that last array element.

Is that the quickest way to do it? No. There is a quicker way, but for this second method to work, you have to have an array in which the order of the elements doesn't matter. Take a look at the code, and you'll see what I mean.

Dim MyArray(9) As Integer

'Remove element from the array
Sub RemoveElement(Index As Integer)
MyArray(Index) = MyArray(UBound(MyArray))
ReDim Preserve MyArray(UBound(MyArray) - 1)
End Sub

Do you see what is happening here? Notice there's no longer a For-Next loop. All I'm doing is snagging the very last array element and putting it in place of the array element I want to remove. Then I use the ReDim command to get rid of the unneeded array element at the end.

## Questions

1.
Write a subroutine that will always delete the first array element.
2.
Write a subroutine that will always delete the last array element
3.
Write a subroutine that will delete 2 array elements, starting at Index.
4.
Write a subroutine that will delete N array elements, starting at Index.
Assign this reference page
One Dimension, Two Dimensions
Parsing a Comma-Separated List

# Featured Games on This Site

Match color, font, and letter in this strategy game
Mastermind variation, with words

# Blogs on This Site

Reviews and book lists - books we love!
The site administrator fields questions from visitors.