Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 728
morgancodes Avatar asked Jan 16 '09 15:01

morgancodes


People also ask

How do you check if an array contains a value in jQuery?

1) Using jQuery If you are someone strongly committed to using the jQuery library, you can use the . inArray( ) method. If the function finds the value, it returns the index position of the value and -1 if it doesn't.

How do you find if an array contains a specific string in jQuery?

inArray( value, array [, fromIndex ] )Returns: Number. Description: Search for a specified value within an array and return its index (or -1 if not found).

How use contains in jQuery?

jQuery :contains() SelectorThe :contains() selector selects elements containing the specified string. The string can be contained directly in the element as text, or in a child element. This is mostly used together with another selector to select the elements containing the text in a group (like in the example above).

How do you use inArray?

PHP in_array() FunctionThe in_array() function searches an array for a specific value. Note: If the search parameter is a string and the type parameter is set to TRUE, the search is case-sensitive.


1 Answers

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; }); 
like image 141
Prestaul Avatar answered Oct 01 '22 16:10

Prestaul