Skip to content

Instantly share code, notes, and snippets.

@magicento
Forked from lovasoa/README.md
Last active August 29, 2015 14:23
Show Gist options
  • Save magicento/2e7b7884e2f5eade13e2 to your computer and use it in GitHub Desktop.
Save magicento/2e7b7884e2f5eade13e2 to your computer and use it in GitHub Desktop.

Fastest function to intersect two arrays in javascript, without dependencies

See benchmarks Usage : array_intersect(arr1, arr2)
function array_intersect() {
var sorted, shortest, ret = [], add, found, obj={}, nOthers;
sorted = Array.prototype.slice.call(arguments).sort(function(i,j){return i.length>j.length;});
nOthers = sorted.length-1;
shortest = sorted[0];
for (var i=nOthers; i>0; --i) {
for (var j=sorted[i].length-1; j>=0; --j) {
obj[sorted[i][j]] = (obj[sorted[i][j]]||0)+1;
}
}
for (var k=shortest.length-1; k>=0; k--) {
if (obj[shortest[k]]===nOthers) {ret.push(shortest[k]);}
}
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment