Efficient way to iterate over elements of array for matching contents of another array Using jQuery I'm trying to find an efficient way to iterate through an array excludeMe and check if elements from another array needsExclusions are contained in the excludeMe array. Not sure if this is the most efficient, but it works. Fiddle here: http://jsfiddle.net/yef9q/3/

//Iterate through needsExclusions for an excludeMe string
//someFlag raised on matching strings

var excludeMe = ["in west", "philadelphia", "born and", "raised"];
var needsExclusions = ["philadelphia", "raised"];
var someFlag = true;

$.each(excludeMe, function(i,val) {
  //alert("value: " + val);
  if ($.inArray(val, needsExclusions) != -1) {
      alert("matching value: " + val);
      someFlag = false;        
  }
});
Your particular example gets 10 times faster by just removing the jQuery and using a for loop and .indexOf() instead of the jQuery versions.  It's also worth stopping the iteration when you find an excluded value since you don't need to look any more once the flag is already set:

var excludeMe = ["in west", "philadelphia", "born and", "raised"];
var needsExclusions = ["philadelphia", "raised"];
var someFlag = true;

for (var i = 0; i &lt; excludeMe.length; i++) {
    if (needsExclusions.indexOf(excludeMe[i]) !== -1) {
        someFlag = false;        
        break;
    }
}


Here's a jsperf that illustrates the speed difference: http://jsperf.com/exclusion-test

If you had a much large data set, then it might pay off to put the needsExclusions values into an object to serve as a direct lookup index (faster than array.indexOf()), but that's probably only faster when the list gets a lot longer because there's setup overhead to build the initial index.