Skip to content

Instantly share code, notes, and snippets.

@jasonrhodes
Created November 29, 2011 22:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasonrhodes/1406796 to your computer and use it in GitHub Desktop.
Save jasonrhodes/1406796 to your computer and use it in GitHub Desktop.
Checking for matching items in two JS arrays
function arrayValueMatch( array1, array2 ) {
var length = array1.length, match = false;
for ( i=0; i<length; i+=1 ) {
if ( array2.indexOf( array1[i] ) > -1 ) {
match = true;
break;
}
}
return match;
}
@abachman
Copy link

You could get rid of some typing with:

function arrayMatchesAny(a, b) { 
  for(var i=0; i<a.length; i++) 
    if (b.indexOf(a[i]) > -1) return true
  return false
}

The same logic you have, but multiple returns lets you skip the break and stored value. Also, if you're only using length once, you may as well only reference it once. Not sure if that affects performance, but it's safe to assume it doesn't.

You could also get clever and extend the array object:

Array.prototype.containsAny = function (other) { 
  for (var i=0; i < this.length; i++) if (other.indexOf(this[i]) > -1) return true; 
  return false; 
}

Or use some, an existing array method:

var a = [1,2,3,4], b = [7, 6, 5, 4]
a.some(function (e) { return b.indexOf(e) > -1; })

indexOf is as good as you're going to get (O(n^2)) unless you keep the arrays sorted and use a binary search to lookup each element of a in b (O(n log n)).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment