jquery version of array.contains

Can jQuery test an array for the presence of an object (either as part of the core functionality or via an avaible plugin)?

Also, I'm looking for something like array.remove, which would remove a given object from an array. Can jQuery handle this for me?


Solution 1:

jQuery.inArray returns the first index that matches the item you searched for or -1 if it is not found:

if($.inArray(valueToMatch, theArray) > -1) alert("it's in there");

You shouldn't need an array.remove. Use splice:

theArray.splice(startRemovingAtThisIndex, numberOfItemsToRemove);

Or, you can perform a "remove" using the jQuery.grep util:

var valueToRemove = 'someval';
theArray = $.grep(theArray, function(val) { return val != valueToRemove; });

Solution 2:

If your list contains a list of elements, then you can use jQuery.not or jQuery.filter to do your "array.remove". (Answer added because of the high google score of your original question).