rss twitter

Array Protoype | removeValue(value:*)

Another prototype I had to use recently and again the Internet didn't provide me any 100% working solution. So here's mine to remove a value in an Array and then automatically change it's keys, so if the value is in the first key everything will move up by one. (0 will be deleted, 1 will be 0 then, 2 -> 1)

I've also written the following Prototypes once:
- remove(index:int) (will be deleting an index and resort)
- insert(index:int, value:*) (will be inserting a key to a specified index and resort)

Example:

Actionscript:
  1. // remove by value
  2. var arr:Array = new Array("a", "b", "c", "d");
  3. arr = arr.removeValue("b"); // pass the value, not index!
  4. trace(arr); // a, c, d

Array.removeValue(value:*):

Actionscript:
  1. Array.prototype.removeValue = function(value:*):Array {
  2.     for(var i:int;i <this.length; i++) {
  3.         if(this[i] === value) {
  4.             var index:int = i;
  5.         }
  6.     }
  7.            
  8.     var original:Array = this.slice();
  9.     if(!index) {
  10.         original.shift();
  11.     } else { 
  12.         var temp:Array = original.splice(index);
  13.         temp.shift();
  14.         original = original.concat(temp);
  15.     }
  16.     return original;
  17. };

3 Responses to “Array Protoype | removeValue(value:*)”

  1. theo_t says:

    Why not just use indexOf + splice ?

    Array.prototype.removeValue = function(value:*):Array
    {
    var o:Array = this.slice(),
    i:int = o.indexOf(value);

    if(i > -1) o.splice(i,1);
    return o;
    }

  2. Marvin Blase says:

    hey theo,
    thanks! doesn't sound bad as well - must admit i haven't checked that yet but will. i guess i was faster writing the prototype than having a look in the livedocs, hehe :)

  3. Stephan says:

    hi, me again ^^ just wanted to say that i have tested it just and it's working perfect. deletes the index and re-orders the array. thanks!

Leave a Reply

Powered by WordPress | Free T-Mobile Phones for Sale | Thanks to Palm Pre Blog, Video Game Music and Get Six Pack Abs