I have two arrays. If a user adds a product, we put it in the ProductArray. If they remove that product, we add it to the ProductArrayRemove array as well as remove it from the product array. (We need to know products that have been added as well as products that have been removed. This requires redundancy.)
ProductArray = JSON.parse(ProductArray);
ProductArrayRemove = JSON.parse(ProductArrayRemove);
When I add and item to the array, I simply do this:
ProductArray.push(ItemID);
ProductArrayRemove.push(ItemID);
But when I remove it, I have to do this:
var len = ProductArray.length;
for (i = 0; i < len; i++) {
ProductID = ProductArray[i];
if (ProductID == ItemID) {
ProductArray.splice(i,1);
break;
}
}
It seems that there should be a better way of accomplishing this task.
Is there a more efficient means of getting rid of a single item (that will always be an integer) from an array?
One different idea that would be super fast to remove an item is to just maintain a single list of items and have a property on each item for whether it is removed or not.
Then to remove an item, all you do it set it’s property
obj.removed = true.The add it back again, you just change the value of that property.
To iterate just the added items, you just skip the ones with the
.removed == trueproperty. To iterate just the removed items, you do just the reverse. Here would be a couple of iterators:And, you would use them like this: