Posts Tagged ‘prototype’

Javascript: Remove values from array prototype

Wednesday, October 29th, 2008

In order to remove certain values or objects from an array many people iterate through it and remove unwanted occurences with the splice() method. It does what you want it to do but it’s pretty cumbersome. There are far easier and simpler ways to remove a certain value from an array.

If we have an array like so: arr = [1,2,2,3,4,5,2,6] and we’d do this: arr.remove(2) we’ll end up with [1,3,4,5,6]. Nobody likes two’s anyway.

Here is how I do it:

Array.prototype.remove = function (subject) {
	var r = new Array();
	for(var i = 0, n = this.length; i < n; i++)
	{
		if(!(this[i]==subject))
		{
			r[r.length] = this[i];
		}
	}
	return r;
}

Why is this better?

  • No copy of the original is needed to do the math
  • It is yet again inherently independent of other array prototypes or methods
  • It runs alot faster ;)

So there you go, another mystery solved.
Take care!