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:
-
// remove by value
-
var arr:Array = new Array("a", "b", "c", "d");
-
arr = arr.removeValue("b"); // pass the value, not index!
-
trace(arr); // a, c, d
Array.removeValue(value:*):
Actionscript:
-
Array.prototype.removeValue = function(value:*):Array {
-
for(var i:int;i <this.length; i++) {
-
if(this[i] === value) {
-
var index:int = i;
-
}
-
}
-
-
var original:Array = this.slice();
-
if(!index) {
-
original.shift();
-
} else {
-
var temp:Array = original.splice(index);
-
temp.shift();
-
original = original.concat(temp);
-
}
-
return original;
-
};



January 21st, 2010
Marvin Blase
Posted in
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;
}
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 :)
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!