JavaScript remove element from array

Tuesday, October 4th 2011 at 9:05pm

So today I was looking for a remove method for Arrays in JavaScript. Sort of a reverse of the Array#push. I’ve scrabbled one together and it goes like this:

Array.prototype.remove = function(element) {
  this.splice(this.indexOf(element), 1)
}

So you could use it like this:

var a = [];

a.push(4);
=> [4]
a.push(6);
=> [4, 6]
a.push(24);
=> [4, 6, 24]

a.remove(6);
a
=> [4, 24]

Comment here or fork this gist on GitHub.

If you've enjoyed this, you should follow me on Twitter.
To read more, head over to break the bit.

Tagged with: