Javascript – jquery version of array.contains

javascriptjquery

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?

Best Solution

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; });