Delete an element from an array in classic ASP

asp-classicvbscript

Given the following array as an example…

arr(0)(0) = 3
arr(0)(1) = name
arr(0)(2) = address
arr(1)(0) = 7
arr(1)(1) = name
arr(1)(2) = address
arr(2)(0) = 14
arr(2)(1) = name
arr(2)(2) = address

I need to delete the middle element (id=7) from the array. I understand that I need to loop through the array and move each record that isnt to be deleted into a new array. I tried like this…

Dim newArr,i
Redim newArr(Ubound(arr))

For i = 0 to Ubound(arr)
    If (CStr(arr(i)(0)) <> 7 ) Then
        newArr(i) = arr(i)
    End if
Next

When debugging this I can see the if statement work so I know only 2 elements are copied but newArr is empty at the end of this. What am I missing. I am a PHP coder that is new to classic asp and Im used to having array functions that make this kind of thing unnecessary. Any help appreciated. Thank you.

Best Answer

You don't need new array, you can just reassign the items and "crop" the array:

Const removalIndex = 1
For x=removalIndex To UBound(arr)-1
    arr(x) = arr(x + 1)
Next
ReDim Preserve arr(UBound(arr) - 1)

This code will remove the array item at index 1 from the main array. If you don't know in advance the index of the item to remove, you can easily find it with a simple loop over the array.

Related Topic