Skip to content

Instantly share code, notes, and snippets.

@kulp
Last active January 1, 2017 02:07
Show Gist options
  • Save kulp/20f65353c99f4b1eba03b8832f046c90 to your computer and use it in GitHub Desktop.
Save kulp/20f65353c99f4b1eba03b8832f046c90 to your computer and use it in GitHub Desktop.
Return the intersection of N arrays
function intersect_n()
{
var aoa = Array.prototype.slice.call(arguments);
var c = [];
var indexes = aoa.map(function(v) { return 0 });
while (aoa.every(function(curr,i) { return indexes[i] < curr.length })) {
var currs = aoa.map(function(curr,i) { return curr[indexes[i]] });
var max = Math.max.apply(null, currs);
aoa.forEach(function(curr,i) { while (curr[indexes[i]] < max) indexes[i]++; });
if (aoa.every(function(curr,i) { return curr[indexes[i]] == max })) {
c.push(max);
indexes.forEach(function(curr,i) { indexes[i]++ });
}
}
return c;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment