Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

More efficient way to remove an element from an array in Actionscript 3

I have an array of objects. Each object has a property called name. I want to efficiently remove an object with a particular name from the array. Is this the BEST way?

  private function RemoveSpoke(Name:String):void {
    var Temp:Array=new Array;
    for each (var S:Object in Spokes) {
      if (S.Name!=Name) {
        Temp.push(S);
      }
    }
    Spokes=Temp;
  }
like image 299
Joshua Avatar asked May 26 '10 19:05

Joshua


3 Answers

If you are willing to spend some memory on a lookup table this will be pretty fast:

private function remove( data:Array, objectTable:Object, name:String):void {
var index:int = data.indexOf( objectTable[name] );
objectTable[name] = null;
data.splice( index, 1 );
}

The test for this looks like this:

private function test():void{

var lookup:Object = {};
var Spokes:Array = [];
for ( var i:int = 0; i < 1000; i++ )
{
    var obj:Object = { name: (Math.random()*0xffffff).toString(16), someOtherProperty:"blah" };
    if ( lookup[ obj.name ] == null )
    {
        lookup[ obj.name ] = obj;
        Spokes.push( obj );
    }
}

var t:int = getTimer();
for ( var i:int = 0; i < 500; i++ )
{
    var test:Object = Spokes[int(Math.random()*Spokes.length)];
    remove(Spokes,lookup,test.name)
}
trace( getTimer() - t );

}

like image 70
Quasimondo Avatar answered Oct 14 '22 18:10

Quasimondo


myArray.splice(myArray.indexOf(myInstance), 1);

like image 43
LeManu Avatar answered Oct 14 '22 16:10

LeManu


The fastest way will be this:

function remove(array: Array, name: String): void {
  var n: int = array.length
  while(--n > -1) {
    if(name == array[n].name) {
      array.splice(n, 1)
      return
    }
   }
}

remove([{name: "hi"}], "hi")

You can also remove the return statement if you want to get rid of all alements that match the given predicate.

like image 35
Joa Ebert Avatar answered Oct 14 '22 16:10

Joa Ebert