hello everyone!
I’m using splice to remove items from an array and keep the indexes numeric, i.e. I don’t want any “null” values in the array.
If I remove one at a time, brilliant. My code is below:
inventory.splice(index,1)
…where index is the index I want to remove.
However, this will change the index of the later items, which is what I want, but it also is a pain because if I want to delete two items from my array at a time how do I know what the index of the second entry is going to be anymore? It might be the same (if it was before the first one we spliced off), or it might now be one less (if it was after).
What’s the best method of deleting these items from the array?
Thanks for the speedy reply, I actually got the message that this thread had been updated just as I’d come up with a solution myself!
Have a look at this and tell me if there are any problems with it:
if(removeIndex1 < removeIndex2){
//--removeIndex2 is a higher index than 1, so the array will be one shorter
removeIndex2-- //--minus 1 to adapt from the first index being deleted
}
inventory.splice(removeIndex1,1)
inventory.splice(removeIndex2,1)
I just check if the second index to be removed is greater than the first. If it is, then I need to knock it down by one.
This was I get away without looping through the entire array!