Removing an item from an array using splice()

hello everyone!
I’m using splice to remove items from an array and keep the indexes numeric, i.e. I don’t want any “null” values in the array.

If I remove one at a time, brilliant. My code is below:

inventory.splice(index,1)

…where index is the index I want to remove.
However, this will change the index of the later items, which is what I want, but it also is a pain because if I want to delete two items from my array at a time how do I know what the index of the second entry is going to be anymore? It might be the same (if it was before the first one we spliced off), or it might now be one less (if it was after).

What’s the best method of deleting these items from the array?

One way would be like this:[FONT=monospace]

var array:Array = [1, 2, 3, null, 4, 5, null, null, 6, null];

for(var i:Number = 0; i < array.length; i++){
    if(array* == null){
        array.splice(i, 1);
        i--;
    }
}

trace(array); // 1,2,3,4,5,6 

[/FONT]

Thanks for the speedy reply, I actually got the message that this thread had been updated just as I’d come up with a solution myself!

Have a look at this and tell me if there are any problems with it:

if(removeIndex1 < removeIndex2){
      //--removeIndex2 is a higher index than 1, so the array will be one shorter
      removeIndex2-- //--minus 1 to adapt from the first index being deleted
}
                
inventory.splice(removeIndex1,1)
inventory.splice(removeIndex2,1)

I just check if the second index to be removed is greater than the first. If it is, then I need to knock it down by one.
This was I get away without looping through the entire array!

Oh, alright, I thought that you were trying to remove all of the non-numeric values from your array instead of one or two specific indices.

The code that you posted looks fine, then!

Cool, thanks. I’m not so good at this array stuff. So I was worried you’d pick big holes in my theory.

thanks for replying! :bounce: