Jump to content

AutoIT - Delete elements from an array selectively


Renderer
 Share

Recommended Posts

Hi there! I have got a small problem regarding arrays. I try to selectively delete some elements of an array. To do that, I create a new array, that contains the indexes of the array, from which they should be deleted. Bellow I've posted some code:

global $iArray[5] = ["H","E","L","L","O"]
global $index[3] = [2,3,4] ; Contains the Indexes of $iArray that should be deleted

_ArrayDisplay($iArray, "Array Before Delete")

;First Attempt:

_ArrayDelete($iArray, $index)
_ArrayDisplay($iArray) ; Failed

;Second Attempt:

for $i = 0 to UBound($index) -1

   _ArrayDelete($iArray, $index[$i])

Next

_ArrayDisplay($iArray); Failed

The question is: How do I get to remove the indexes 2,3,4 contained by ($index array) from the main array ($iArray)? Thanks in advance!

Link to comment
Share on other sites

The array passed to _ArrayDelete must be 1 based with count in 0.

#include <Array.au3>

local $iArray[5] = ["H","E","L","L","O"]
Local $index[4] = [3,2,3,4] ; Contains the Indexes of $iArray that should be deleted

_ArrayDisplay($iArray, "Array Before Delete")

_ArrayDelete($iArray, $index)
_ArrayDisplay($iArray) ; Don't fail anymore

 

Link to comment
Share on other sites

Also remember when deleting within a loop (using +1) to sort your [indexes array] from largest to smallest, _ArraySort($index, 1) otherwise you will get unexpected results as the original arrays bounds are also changed when modifying the array, for example:

global $iArray[5] = ["A","B","C","D","E"]
global $index[3] = [2,3,4] ; Contains the Indexes of $iArray that should be deleted

_ArrayDelete($iArray, $index[0]) ;~ Deletes 2nd index "C"
;~ Result: $iArray[4] = ["A","B","D","E"]
_ArrayDelete($iArray, $index[1]) ;~ Deletes 3rd index "E"
;~ Result: $iArray[3] = ["A","B","D"]
_ArrayDelete($iArray, $index[2]) ;~ Error 5 - $vRange content is outside array bounds
;~ Result: $iArray[3] = ["A","B","D"]

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...