Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest code for array intersection in javascript

What's the simplest, library-free code for implementing array intersections in javascript? I want to write

intersection([1,2,3], [2,3,4,5]) 

and get

[2, 3] 
like image 644
Peter Avatar asked Dec 11 '09 03:12

Peter


2 Answers

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

const filteredArray = array1.filter(value => array2.includes(value)); 

For older browsers, with Array.prototype.indexOf and without an arrow function:

var filteredArray = array1.filter(function(n) {     return array2.indexOf(n) !== -1; }); 

NB! Both .includes and .indexOf internally compares elements in the array by using ===, so if the array contains objects it will only compare object references (not their content). If you want to specify your own comparison logic, use Array.prototype.some instead.

like image 82
Anon. Avatar answered Oct 05 '22 09:10

Anon.


Destructive seems simplest, especially if we can assume the input is sorted:

/* destructively finds the intersection of   * two arrays in a simple fashion.    *  * PARAMS  *  a - first array, must already be sorted  *  b - second array, must already be sorted  *  * NOTES  *  State of input arrays is undefined when  *  the function returns.  They should be   *  (prolly) be dumped.  *  *  Should have O(n) operations, where n is   *    n = MIN(a.length, b.length)  */ function intersection_destructive(a, b) {   var result = [];   while( a.length > 0 && b.length > 0 )   {        if      (a[0] < b[0] ){ a.shift(); }      else if (a[0] > b[0] ){ b.shift(); }      else /* they're equal */      {        result.push(a.shift());        b.shift();      }   }    return result; } 

Non-destructive has to be a hair more complicated, since we’ve got to track indices:

/* finds the intersection of   * two arrays in a simple fashion.    *  * PARAMS  *  a - first array, must already be sorted  *  b - second array, must already be sorted  *  * NOTES  *  *  Should have O(n) operations, where n is   *    n = MIN(a.length(), b.length())  */ function intersect_safe(a, b) {   var ai=0, 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(a[ai]);        ai++;        bi++;      }   }    return result; } 
like image 45
atk Avatar answered Oct 05 '22 10:10

atk