[SOLVED] How to remove entity from array?

I use this array:

this.visibleTargets = [];

I can add an entity with:

this.visibleTargets.push(targetEntity);

I can search if the entity already is in the array with:

this.visibleTargets.includes(targetEntity)

But I can’t manage to remove the entity from the array…

To remove an item from a Javascript array you must first find its position (index) in the array.

Here is an example:

            var index = this.visibleTargets.indexOf(targetEntity);
            if (index !== -1) {
                this.visibleTargets.splice(index, 1);
            }

That works. Thank you!

1 Like

I have adjusted your sample code to:

this.visibleTargets.splice(this.visibleTargets.indexOf(targetEntity));

It seems to work, so can I use it that way?

// this will remove targetEntity from the visibleTargets array
// if you are certain that it exists in it.
this.visibleTargets.splice(this.visibleTargets.indexOf(targetEntity), 1);

Yes but two things to take care first:

  • You need to pass the second argument to splice which is the number of items you want to remove at this position, in your case that would be 1. Otherwise all elements from that position till the end of the array will be removed.
  • You should make sure that this entity exists in this array, otherwise -1 will be passed by the indexOf method as the first argument of splice. That will make splice work in reverse, starting to remove elements from the end of the array.

So yes, use it in a single line but do take care of those things.

1 Like

Thanks for your update. I Will add your first point to the code. I already use a check before:

if (this.visibleTargets.includes(targetEntity)) {
    // remove from array
}
1 Like