Simplest code for array intersection in javascript

Use a combination of Array.prototype.filter and Array.prototype.indexOf:

<span class="pln">array1</span><span class="pun">.</span><span class="pln">filter</span><span class="pun">(</span><span class="pln">value </span><span class="pun">=></span> <span class="pun">-</span><span class="lit">1</span> <span class="pun">!==</span><span class="pln"> array2</span><span class="pun">.</span><span class="pln">indexOf</span><span class="pun">(</span><span class="pln">value</span><span class="pun">));</span>

 

Performance Benchmark:

http://jsfiddle.net/321juyLu/2/

Array intersection, difference and union in ES6

arrA = [“Σὲ”, “γνωρίζω”, “ἀπὸ”, “τὴD”, “κόψη”, “and”, “the”, “word”, “was”, “Test”];

arrB = [“Σὲ”, “γνωρίζω”, “ἀπD”, “τὴD”, “κόψη”, “and”, “the”, “word”, “was”, “test”];

function normalize(word){

return word.toLowerCase();

}

normalizedA= arrA.filter(normalize);

normalizedB= arrB.filter(normalize);

common_words = normalizedA.filter(x => normalizedB.includes(x));

console.log(common_words);

Testing

mainList = [-11, -1, 1, 2, 3, 4, 5, 6, 20, 44, 87, 99, 100];
toSearchList = [-1, 1, 4];

String Testing

mainList = [‘In’,’the’,’beginning’,’was’,’the’,’word’];
toSearchList =[‘In’,’the’,’beginning’,’has’,’the’,’word’];

function IndexOfLoop(x, y){
var ret = [];
for (var i = 0; i < x.length; i++) {
if (y.indexOf(x[i]) !== -1) {
ret.push(i);
}
}
return ret;
}

function IndexOfFilter(x, y){
return x.filter(function (i) { return y.indexOf(i) !== -1; })
}

function SimpleJsLoops(x, y){
var ret = [];
for (var i = 0; i < x.length; i++) {
for (var z = 0; z < y.length; z++) {
if (x[i] == y[z]) {
ret.push(i);
break;
}
}
}
return ret;
}

function SimpleJsLoops2(x, y){
var ret = [],
xLen = x.length,
yLen = y.length;
for (var i = 0; i < xLen; i++) {
for (var z = 0; z < yLen; z++) {
if (x[i] == y[z]) {
ret.push(i);
break;
}
}
}
return ret;
}

function intersection(x, y) {
x.sort();
y.sort();
var i = j = 0;
var ret = [];
while (i < x.length && j < y.length) {
if (x[i] < y[j]) i++;
else if (y[j] < x[i]) j++;
else {
ret.push(i);
i++, j++;
}
}
return ret;
}

function intersect_safe(a, b)
{
var ai = bi= 0;
var result = [];

while( ai < a.length && bi < b.length ){
if (a[ai] < b[bi] ){ ai++; }
else if (a[ai] > b[bi] ){ bi++; }
else /* they’re equal */
{
result.push(ai);
ai++;
bi++;
}
}

return result;
}

var arrayContains = Array.prototype.indexOf ?
function(arr, val) {
return arr.indexOf(val) > -1;
} :
function(arr, val) {
var i = arr.length;
while (i–) {
if (arr[i] === val) {
return true;
}
}
return false;
};

function arrayIntersection() {
var val, arrayCount, firstArray, i, j, intersection = [], missing;
var arrays = Array.prototype.slice.call(arguments);
firstArr = arrays.pop();
if (firstArr) {
j = firstArr.length;
arrayCount = arrays.length;
while (j–) {
val = firstArr[j];
missing = false;
i = arrayCount;
idx = null;
while (!missing && i–) {
idx = arrays[i].indexOf(val);
if ( !arrayContains(arrays[i], val) ) {
missing = true;
}
}
if (!missing) {
intersection.push(idx);
}
}
}
return intersection;
}

function intersect(array1, array2) {
var result = [];
// Don’t destroy the original arrays
var a = array1.slice(0);
var b = array2.slice(0);
var aLast = a.length – 1;
var bLast = b.length – 1;
while (aLast >= 0 && bLast >= 0) {
if (a[aLast] > b[bLast] ) {
a.pop();
aLast–;
} else if (a[aLast] < b[bLast] ){
b.pop();
bLast–;
} else /* they’re equal */ {
result.push(a.pop());
b.pop();
aLast–;
bLast–;
}
}
return result;
}

function seenIntersection(array1,array2) {
var seen=[],
result=[];
for (var i = 0; i < array1.length; i++) {
seen[array1[i]] = true;
}
for (var i = 0; i < array2.length; i++) {
if ( seen[array2[i]])
result.push(array2[i]);
}
return result;
}

function ecmascript(array1,array2) {
return array1.filter(value => -1 !== array2.indexOf(value));
}

///////////////////////////////////////////////////////////////////////////
//test the functions, to see that they return correct results
/////////////////////////////////////////////////////////////////
document.write(IndexOfLoop(toSearchList, mainList)+'<br>’);
document.write(IndexOfFilter(toSearchList, mainList)+'<br>’);
document.write(SimpleJsLoops(toSearchList, mainList)+'<br>’);
document.write(SimpleJsLoops2(toSearchList, mainList)+'<br>’);
document.write(intersection(toSearchList, mainList)+'<br>’);
document.write(intersect_safe(toSearchList, mainList)+'<br>’);
document.write(arrayIntersection(toSearchList, mainList)+'<br>’);
document.write(intersect(toSearchList, mainList)+'<br>’);
document.write(_.intersection(toSearchList, mainList)+'<br>’);
document.write(seenIntersection(toSearchList, mainList)+'<br>’);
document.write(ecmascript(toSearchList, mainList)+'<br>’);

///////////////////////////////////////////////////////////////////////////
//Banchmark the functions.
/////////////////////////////
JSLitmus.test(‘indexOf loop’, function () { IndexOfLoop(toSearchList, mainList) });
JSLitmus.test(‘indexOf filter’, function () { IndexOfFilter(toSearchList, mainList) });
JSLitmus.test(‘Simple js loops’, function () { SimpleJsLoops(toSearchList, mainList) });
JSLitmus.test(‘Simple js loops 2’, function () { SimpleJsLoops2(toSearchList, mainList) });
JSLitmus.test(‘intersection’, function () {intersection(toSearchList, mainList); });
JSLitmus.test(‘intersect_safe’, function () {intersect_safe(toSearchList, mainList); });
JSLitmus.test(‘all the way down’, function () {arrayIntersection(toSearchList, mainList); });
JSLitmus.test(‘intersect’, function () {intersect(toSearchList, mainList); });
JSLitmus.test(‘_underscore’, function () {_.intersection(toSearchList, mainList); });
JSLitmus.test(‘seenIntersection’, function () {seenIntersection(toSearchList, mainList); });
JSLitmus.test(‘ecmascript’, function () {ecmascript(toSearchList, mainList); });