jquery version of array.contains

JavascriptJquery

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 - Javascript

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

Solution 3 - Javascript

I found way to remove object:

foot = { bar : 'test'};
delete foot[bar];

Solution 4 - Javascript

This is not jQuery, but in one line you can add a handy 'contains' method to arrays. I find this helps with readability (especially for python folk).

Array.prototype.contains = function(a){ return this.indexOf(a) != -1 }

example usage

 > var a = [1,2,3]
 > a.contains(1)
true
 > a.contains(4)
false

Similarly for remove

Array.prototype.remove = function(a){if (this.contains(a)){ this.splice(this.indexOf(a),1)}; return this}

> var a = [1,2,3]
> a.remove(2)
[1,3]

Or, if you want it to return the thing removed rather than the altered array, then

Array.prototype.remove = function(a){if (this.contains(a)){ return this.splice(this.indexOf(a),1)}}

> var a = [1,2,3]
> a.remove(2)
[2]
> a
[1,3]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmorgancodesView Question on Stackoverflow
Solution 1 - JavascriptPrestaulView Answer on Stackoverflow
Solution 2 - JavascriptBryan LarsenView Answer on Stackoverflow
Solution 3 - JavascriptLiutasView Answer on Stackoverflow
Solution 4 - Javascriptuser2013483View Answer on Stackoverflow