Skip to content

Instantly share code, notes, and snippets.

@bitifet
Created March 4, 2015 12:28
Show Gist options
  • Save bitifet/e19692683e4c746925d1 to your computer and use it in GitHub Desktop.
Save bitifet/e19692683e4c746925d1 to your computer and use it in GitHub Desktop.
Array (or object) values intersection.
// Exapmle var foo = intersect({foo: [1, 2, 5, 8], bar: {two: 2, tree: 3, four: 4, five: 5, six: 6}});
function intersect (arrList) { // Calculate intersection of multiple array or object values: //{{{
var l = Object.keys(arrList).length; // Also accepts regular objects as input.
var index = {};
for (var i in arrList) {
for (var j in arrList[i]) {
var v = arrList[i][j];
if (index[v] === undefined) index[v] = 0;
index[v]++;
};
};
var retv = [];
for (var i in index) {
if (index[i] == l) retv.push(i);
};
return retv;
};//}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment