0

Is it possible to check if multiple items are contained within an array using jquery's inArray function?

if ($.inArray('foo' && 'bar', array) == -1) {
    // Neither foo or bar in array
});

Thanks

3 Answers 3

7

With jQuery.inArray, you can (quoting) :

Search for a specified value within an array and return its index (or -1 if not found).

Looking at that documentation page, it doesn't seem you can pass more than one value to that function.


So, why not call that function twice : one time for 'foo', and one time for 'bar' :

if ($.inArray('foo', array) == -1 && $.inArray('bar', array) == -1) {
    // Neither foo or bar in array
}
Sign up to request clarification or add additional context in comments.

3 Comments

Just thought there might be a tidier way if say I want to pass 20 items to check.
If you have several items, you could put those in an array -- and, then, loop over that array of items, calling jQuery.inArray for each item.
Yep that's probably the best way of going about it!
2
var arr= ['foo','bar'];
var length = arr.length;
for ( var i = 0 ;  i < length; i++ ) {
  if(jQuery.inArray(arr[i],array) > -1) {
   // do whatever you want.
  }

}

Comments

0

What about?

if (array.join(",").match(/foo|bar/gi).length == 2){
   //
}

or

var find = ["foo","bar"], exp = new RegExp(find.join("|"), "gi");
if (array.join(",").match(exp).length == find.length){
    //
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.