Last active
January 1, 2017 02:07
-
-
Save kulp/20f65353c99f4b1eba03b8832f046c90 to your computer and use it in GitHub Desktop.
Return the intersection of N 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 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