remove value from array


/ Published in: ASP

This function returns the array with all instances of the specified value removed


Copy this code and paste it in your HTML
  1. 'This function returns a copy of the array with all instances of the specified value removed
  2. function removeValueFromArray(byval arrayName, valueToRemove)
  3. amountFound = 0 'keeps track of how many it found so that it knows what size to redim the array at the end
  4. topIndex = ubound(arrayName) 'hold the value of the ubound in a variable so that you can decrement it when you find the value to remove
  5. for i = 0 to ubound(arrayName)
  6. if i > topIndex then 'this keeps the loop from checking past the topIndex. keeps the loop from being infinite when the last value
  7. exit for ' exit the loop when you have reached the end of the checked values
  8. end if
  9. if arrayName(i) = valueToRemove then
  10. topIndex = topIndex - 1 'decrement the topIndex when you shift down so that it doesn't check the duplicated values at the end of the array
  11. amountFound = amountFound + 1 ' the value has been found so increment
  12. for j = i to (ubound(arrayName) - 1) 'shift the array values left to overwrite the value to remove
  13. arrayName(j) = arrayName(j + 1)
  14. next
  15. 'if the next element was equal to valueToRemove you have to go back and get rid of it too
  16. if arrayName(i) = valueToRemove then
  17. i = i - 1 ' this gets incremented at the beginning of the loop so don't worry about negative values
  18. end if
  19. end if
  20. next
  21. redim preserve arrayName(ubound(arrayName) - amountFound)
  22. removeValueFromArray = arrayName
  23. end function

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.