[javascript] Simplest code for array intersection in javascript

_x000D_
_x000D_
// Return elements of array a that are also in b in linear time:_x000D_
function intersect(a, b) {_x000D_
  return a.filter(Set.prototype.has, new Set(b));_x000D_
}_x000D_
_x000D_
// Example:_x000D_
console.log(intersect([1,2,3], [2,3,4,5]));
_x000D_
_x000D_
_x000D_

I recommend above succinct solution which outperforms other implementations on large inputs. If performance on small inputs matters, check the alternatives below.

Alternatives and performance comparison:

See the following snippet for alternative implementations and check https://jsperf.com/array-intersection-comparison for performance comparisons.

_x000D_
_x000D_
function intersect_for(a, b) {_x000D_
  const result = [];_x000D_
  const alen = a.length;_x000D_
  const blen = b.length;_x000D_
  for (let i = 0; i < alen; ++i) {_x000D_
    const ai = a[i];_x000D_
    for (let j = 0; j < blen; ++j) {_x000D_
      if (ai === b[j]) {_x000D_
        result.push(ai);_x000D_
        break;_x000D_
      }_x000D_
    }_x000D_
  } _x000D_
  return result;_x000D_
}_x000D_
_x000D_
function intersect_filter_indexOf(a, b) {_x000D_
  return a.filter(el => b.indexOf(el) !== -1);_x000D_
}_x000D_
_x000D_
function intersect_filter_in(a, b) {_x000D_
  const map = b.reduce((map, el) => {map[el] = true; return map}, {});_x000D_
  return a.filter(el => el in map);_x000D_
}_x000D_
_x000D_
function intersect_for_in(a, b) {_x000D_
  const result = [];_x000D_
  const map = {};_x000D_
  for (let i = 0, length = b.length; i < length; ++i) {_x000D_
    map[b[i]] = true;_x000D_
  }_x000D_
  for (let i = 0, length = a.length; i < length; ++i) {_x000D_
    if (a[i] in map) result.push(a[i]);_x000D_
  }_x000D_
  return result;_x000D_
}_x000D_
_x000D_
function intersect_filter_includes(a, b) {_x000D_
  return a.filter(el => b.includes(el));_x000D_
}_x000D_
_x000D_
function intersect_filter_has_this(a, b) {_x000D_
  return a.filter(Set.prototype.has, new Set(b));_x000D_
}_x000D_
_x000D_
function intersect_filter_has_arrow(a, b) {_x000D_
  const set = new Set(b);_x000D_
  return a.filter(el => set.has(el));_x000D_
}_x000D_
_x000D_
function intersect_for_has(a, b) {_x000D_
  const result = [];_x000D_
  const set = new Set(b);_x000D_
  for (let i = 0, length = a.length; i < length; ++i) {_x000D_
    if (set.has(a[i])) result.push(a[i]);_x000D_
  }_x000D_
  return result;_x000D_
}
_x000D_
_x000D_
_x000D_

Results in Firefox 53:

  • Ops/sec on large arrays (10,000 elements):

    filter + has (this)               523 (this answer)
    for + has                         482
    for-loop + in                     279
    filter + in                       242
    for-loops                          24
    filter + includes                  14
    filter + indexOf                   10
    
  • Ops/sec on small arrays (100 elements):

    for-loop + in                 384,426
    filter + in                   192,066
    for-loops                     159,137
    filter + includes             104,068
    filter + indexOf               71,598
    filter + has (this)            43,531 (this answer)
    filter + has (arrow function)  35,588
    

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to data-structures

Program to find largest and second largest number in array golang why don't we have a set datastructure How to initialize a vector with fixed length in R C compiling - "undefined reference to"? List of all unique characters in a string? Binary Search Tree - Java Implementation How to clone object in C++ ? Or Is there another solution? How to check queue length in Python Difference between "Complete binary tree", "strict binary tree","full binary Tree"? Write code to convert given number into words (eg 1234 as input should output one thousand two hundred and thirty four)

Examples related to intersection

How to calculate the intersection of two sets? Removing duplicates in the lists Intersect Two Lists in C# How can I get the intersection, union, and subset of arrays in Ruby? Intersection and union of ArrayLists in Java How to find list intersection? Simplest code for array intersection in javascript Find intersection of two nested lists?