Created
November 29, 2011 22:10
-
-
Save jasonrhodes/1406796 to your computer and use it in GitHub Desktop.
Checking for matching items in two JS arrays
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You could get rid of some typing with:
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:
Or use some, an existing array method:
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)).