Javascript: Remove values from array prototype

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!

Tags: , ,

13 Responses to “Javascript: Remove values from array prototype”

  1. Sander wrote:

    That’s a nice one!

  2. kohalza wrote:

    you’ve got a bug in your code.
    Try: arr.remove(true)
    It will remove all non false values from the array. No quite what we wanted.
    You need to use the identity operator === instead of ==

  3. Rene wrote:

    Good one, thanks!

    @kohalza. True represents any value, so if you remove true, you remove anything that has a value in it. It is not a bug, it is a feature. As far as i know, all programming languages have this. Because true represents anything. If you do remove(false) it will remove any row with nothing in it.

    So use it wisely, and correct

  4. Cederash wrote:

    Красавчег! Пиши исчё!

  5. Ferinannnd wrote:

    Захватывающе. Зачет! и ниипет!

  6. Avertedd wrote:

    красиво, сделал! Благодарю!!!

  7. Yorikk wrote:

    И придратся не к чему, а я так люблю покритиковать…

  8. Dimmka wrote:

    Достаточно интересная и познавательная тема

  9. pinepain wrote:

    Maybe this one will be god? It just modify existent Array obj.

    Array.prototype.del = function (item) {
    this.sort(function (a, b) {return a == item;});
    var deleted = 0;
    while (this[this.length-1] == item) {
    this.pop();
    deleted++;
    }
    return deleted;
    }

  10. IllepkaKhah wrote:

    газ и уголь в России

    Занятно-занятно, нигде заранее для такое не натыкался.

  11. dozorspb wrote:

    Комплекс текстов хороший удачный, закину сайт в закладки!

  12. каталог rss wrote:

    участник rss

  13. Octavian wrote:

    “No copy of the original is needed to do the math”
    Right before your “return r” you got one n-length array and one (n-1)length array.
    It’s almost the same as having a copy of your initial array.

    Except that, your method only covers the integer-indexed arrays. It’s doing its job for that, but what about hash tables?

Leave a Reply