2 min read

JS: quickly removing an arbitrary element from an Array

Paul Kinlan

Paul Kinlan

Lead of Chrome DevRel

Unless I am mistaken (and I could be), Arrays in JavaScript have no direct way to delete an arbitrary element. I had a little problem where I knew the index of the item I want to remove, there was no easy way to do this. I can't just say 'array.remove(5)'.

A way that I have seen some people use get around this problem is to use Array.prototype.join to push the contents into a string, then do a string replace on an element value and then String.split to produce the array with the element removed. It is a bit of a hack. Heck, it is a lot of a hack!

If your browser supports parts of ECMA Script 5, then Array object now has some extra methods for you to use, including filter(). Filter allows you to specify a function that is called for every item in the list, and for that value you can say if you want it in the result set. So it is ideal to solve the problem of removing an element from the list if you know it's value.

var valToRemove = "hello";
var values = ["Ah", "hello", "world"];
values = values.filter(function(i) {
  if(i != valToRemove) return true;
  else return false;
  });

Pretty easy, and quick given a small array. Obviously, this little piece of code will remove every element from the list with the value I am looking for – but this is ok for my code.

Still, there isn't an easy way to remove the nth element from a list unless you shift or pop your way through the array. But that is another story.

Stay in the loop.

I'm trialing a newsletter. Join for monthly insights into web dev, Chrome, and the open web.

alternate_email

Get in touch

Open to chat about Chrome or Web development.

Book a consultation