Jordan Jordan - 1 year ago 80
Javascript Question

JavaScript - Arrays - Deleting elements from an array

I've looked up arrays and how they work, looked at a lot of other stackoverflow questions on this same topic but the answer still doesn't remain clear. How can I remove a specified element from an array?

I've tried:

array.splice(i, 5);
delete array[5]; //doesn't actually delete - I know

1 of 2 things happen every time. 1. The whole array is deleted with either of the first 2 methods mentioned above. or 2. Everything before/after the element specified is removed.

For example, I had an array that contained a Clash Royale deck:

var deck = ["Barbarians", "Goblin_Barrel", "Inferno_Tower", "Fireball", "Zap", "Hog_Rider", "Spear_Goblins", "Minion_Horde"];

Then if I wanted to remove, lets say, Fireball, then I did:


And the array now looked like this:

deck = [];

So, to restate my question. How do I remove a specified, and only the specified, element from an array?

Answer Source

Check the usage for splice in a JavaScript reference. You need to pass in the index of the thing to delete, then how many things to delete.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download