Skip to content

Instantly share code, notes, and snippets.

@davidrautert
Created October 15, 2012 16:34
Show Gist options
  • Save davidrautert/3893466 to your computer and use it in GitHub Desktop.
Save davidrautert/3893466 to your computer and use it in GitHub Desktop.
JS: Multi-array intersect
/*
** 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