views:

9182

answers:

3

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?

thanks,

-Morgan

+20  A: 

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; });
Prestaul
Thanks Prestaul. Thing is, I don't know the index of the object I need to remove, so I think I still need array.remove.
morgancodes
oh, cool. Right there in the docs under "utilities". "RTFM" would have been an acceptalbe answer:) thanks for pointing me there though. I think jquery.grep may give me the remove functionality I need.
morgancodes
@morgancodes, it will indeed! I was adding that to my answer as you were commenting.
Prestaul
also: theArray.splice($.inArray(value, theArray), 1);
thenduks
@thenduks, I avoided that because it only works if your array contents are all unique. It only removes the first match.
Prestaul
BTW: "theArray.splice($.inArray(value, theArray), 1);" only works if the item is in the list.
Amir
+1  A: 

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).

Bryan Larsen
A: 

I came to this page searching ways to remove a value from an array. What I discovered was that I should have been using an object all along.

What I really wanted was an associative array. Objects worked out much better.

However if you want to sort or find the length of your values the array is probably the correct tool.

See http://www.quirksmode.org/js/associative.html

Keyo