At 9/22/23 06:50 PM, Nabella wrote:
At 9/22/23 06:28 PM, MSGhero wrote:
Some people iterate through the array backwards, so if you remove and splice an item out, it won't affect all of the other ones. Other people add all of the things that need to be spliced to another array, and then iterate through there removing things from the main array.
Wait, nvm, I googled it, found an example, imitated it, and it seemingly solved the problem.
Still do elaborate on the two arrays, though. I would appreciate the insight.
Not entirely sure if I understood what @MSGHero meant - feel free to correct me if I didn't.
But I guess it would be something like this?
var array:Array = [1, 2, 3, 4, 5, 6, 7, 8];
// array to store items to splice
var spliceResult:Array = [];
for (var i:Number = 0; i < array.length; ++i) {
// say we want to remove all even numbers
if(array[i] % 2 == 0) {
spliceResult.push(array[i]);
}
}
// now loop through both arrays to remove them from the main array
for each(var number:Object in spliceResult) {
for (var i:Number = 0; i < array.length; ++i) {
if(array[i] == number) {
array.splice(i, 1);
}
}
}
Which would indeed remove all the numbers, but is probably inefficient so I might've been thinking of something else.
An alternative is to filter out the elements to be spliced by taking the inverse -- that is, creating a new array consisting of elements that should be kept rather than removed. From the above example..
var array:Array = [1, 2, 3, 4, 5, 6, 7, 8];
var results:Array = [];
for (var i:Number = 0; i < array.length; ++i) {
// say we again want to remove even numbers; then add the odd ones to results
if (array[i] % 2 != 0) {
results.push(array[i]);
}
}
// toss the old array by assigning it to `results`
array = results
In AS3 and JavaScript you could use the inbuilt array methods to simplify this down:
var array = [1, 2, 3, 4, 5, 6, 7, 8];
var results = array.filter(function(item) {
return item % 2 != 0
})
but AS2 doesn't have that syntactic sugar unfortunately.