views:

60

answers:

3

Is there a method to be able to remove an item from an JavaScript array like from this array:

var ary = ['three', 'seven', 'eleven'];

And I do an function like whereas:

removeItem('seven', ary);

I've looked into splice() but that only removes by the position number, where I need something to remove an item by it's value.

+5  A: 

You're looking for the indexOf method
For example:

var index = array.indexOf(item);
array.splice(index, 1);

Note that you'll need to add it for IE.

SLaks
And loop on it while the index isn't `-1`
Colin Hebert
A: 

indexOf is an option, but it's implementation is basically searching the entire array for the value, so execution time grows with array size. (so it is in every browser I guess, I only checked Firefox).

I haven't got an IE6 around to check, but I'd call it a safe bet that you can check at least a million array items per second this way on almost any client machine. If [array size]*[searches per second] may grow bigger than a million you should consider a different implementation.

Basically you can use an object to make an index for your array, like so:

var index={'three':0, 'seven':1, 'eleven':2};

Any sane JavaScript environment will create a searchable index for such objects so that you can quickly translate a key into a value, no matter how many properties the object has.

This is just the basic method, depending on your need you may combine several objects and/or arrays to make the same data quickly searchable for different properties. If you specify your exact needs I can suggest a more specific data structure.

eBusiness
A: 

This can be a global function or a method of a custom object, if you aren't allowed to add to native prototypes. It removes all of the items from the array that match any of the arguments.

Array.prototype.remove= function(){
    var what, a= arguments, L= a.length, ax;
    while(L && this.length){
        what= a[--L];
        while((ax= this.indexOf(what))!= -1){
            this.splice(ax, 1);
        }
    }
    return this;
}

var ary = ['three', 'seven', 'eleven'];

ary.remove('seven')

/*  returned value: (Array)
three,eleven
*/

To make it a global-

function removeA(arr){
    var what, a= arguments, L= a.length, ax;
    while(L> 1 && arr.length){
        what= a[--L];
        while((ax= arr.indexOf(what))!= -1){
            arr.splice(ax, 1);
        }
    }
    return arr;
}
var ary= ['three','seven','eleven'];
removeA(ary,'seven')


/*  returned value: (Array)
three,eleven
*/

And to take care of IE8 and below-

if(!Array.prototype.indexOf){
    Array.prototype.indexOf= function(what, i){
        i= i || 0;
        var L= this.length;
        while(i< L){
            if(this[i]=== what) return i;
            ++i;
        }
        return -1;
    }
}
kennebec