AS3 Quick Tip – Remove a specific item from an array.

I’ve been working on a project today and needed a function to remove a specific item from an array. This is what I came up with, so I thought I’d share it here.

var myArrayOfLetters:Array = ["a","b","c","c","d","e","f","g","c"];
removeItemArray(myArrayOfLetters,"c");
//This will remove all instances of "c" from your array - so you will end up with
//a,b,d,e,f,g
 
function removeItemArray(thearray, theItem):void{
	trace("Remove "+theItem+" from "+thearray);
	for(var i:int=0; i

This will remove all instances of theItem from your array. If you know there will only be one instance of the item in the array, you can add "break;" to the conditional in the loop to save CPU.

var myArrayOfLetters:Array = ["a","b","c","d","e","f","g"];
removeItemArray(myArrayOfLetters,"c");
//This will remove the first instance of "c" from your array - so you will end up with
//a,b,d,e,f,g

function removeItemArray(thearray , theItem):void{
	trace("Remove "+theItem+" from "+thearray );
	for(var i:int=0; i

Hope you find it useful.
Lawrie.

7 thoughts on “AS3 Quick Tip – Remove a specific item from an array.”

  1. You actually can’t do that safely without the break, because your .splice() is altering the indices of the array elements while you’re still iterating over them.

    You’re skipping over the next item in line every time you remove one. Try just removing every item in the array to see that in action.

  2. Ah good spot Matt, thanks for pointing it out. I’ve added in “i-=1” after the splice which should counteract the altering of the indices.

  3. start at the end of the array and count down to 0 as long as you don’t match the search term. That way you don’t need to decrement i

  4. como faço para remover campos vazios dinamicamente

    exeplo:
    [‘a’,’ b’,’c’ ,’ ‘,’e’,’ ‘]

    resuldado:
    [‘a’,’ b’,’c’ ,’e’,]

  5. Para eliminar elementos en blanco, tendrá que utilizar la función superior (para asegurarse de que se realiza un bucle a través de todos los elementos de la matriz) y pasar una cadena vacía como su segundo argumento. Por lo tanto –
    myArrayOfLetters var: Array = [‘a’, ‘b’, ‘c’, ”, ‘e’, ”];
    removeItemArray (myArrayOfLetters, “”);
    = [‘a’, ‘b’, ‘c’, ‘e’]

Leave a Reply

Your email address will not be published.