Created
October 15, 2012 16:34
-
-
Save davidrautert/3893466 to your computer and use it in GitHub Desktop.
JS: Multi-array intersect
This file contains 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
/* | |
** intersect.js | |
** intersect multiple arrays | |
** Usage: | |
var arr1 = ['hey', 'you', 'guys', 'test', 'there']; | |
var arr2 = ['there', 'you']; | |
var arr3 = ['some', 'there', 'you', 'thrice', 'hey', 'huzzah']; | |
intersect(arr1, arr2, arr3); | |
*/ | |
function intersect() { | |
if(arguments.length == 1) { | |
return arguments[0]; | |
} | |
var temp = []; | |
var smallest = arguments[0]; | |
var exclude = 0; | |
for(var i=0; i<arguments.length; i++) { | |
if(arguments[i].length < smallest.length) { | |
smallest = arguments[i]; | |
exclude = i; | |
} | |
} | |
for(var i=0; i<smallest.length; i++) { | |
var found = true; | |
for(var n=0; n<arguments.length; n++) { | |
if(n != exclude) { | |
if(arguments[n].indexOf(smallest[i]) == -1) { | |
found = false | |
} | |
} | |
} | |
if(found) { | |
temp.push(smallest[i]); | |
} | |
} | |
return temp; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment