SoFunction
Updated on 2025-02-28

Sample code for JS array intersection, union, difference set

This article introduces JS array intersection, union, and difference. It is shared with you. The details are as follows:

Since the ES5 method will be used below, the lower version will be compatible, so you should first add the corresponding polyfill

 =  || function (searchElement, fromIndex) {
  var index = -1;
  fromIndex = fromIndex * 1 || 0;
  for (var k = 0, length = ; k < length; k++) {
    if (k >= fromIndex && this[k] === searchElement) {
      index = k;
      break;
    }
  }
  return index;
};

 =  || function (fn, context) {
  var arr = [];
  if (typeof fn === "function") {
    for (var k = 0, length = ; k < length; k++) {
      (context, this[k], k, this) && (this[k]);
    }
  }
  return arr;
};

Depend on array deduplication method:

// Deduplication of array = function() {
  var n = {}, r = [];
  for (var i = 0; i &lt; ; i++) {
    if (!n[this[i]]) {
      n[this[i]] = true;
      (this[i]); 
    }
  }
  return r;
}

Intersection

The intersection element consists of elements that belong to both set A and set B.

 = function(arr1, arr2) {
  if((arr1) === "[object Array]" &amp;&amp; (arr2) === "[object Array]") {
    return (function(v){ 
     return (v)!==-1 
    }) 
  }
}
//How to use([1,2,3,4], [3,4,5,6]); // [3,4]

Collect

The union element consists of deduplication of all elements in the set A and set B.

 = function(arr1, arr2) {
  if((arr1) === "[object Array]" &amp;&amp; (arr2) === "[object Array]") {
    return (arr2).unique()
  }
}
//How to use([1,2,3,4], [1,3,4,5,6]); // [1,2,3,4,5,6]

Difference set

A's difference set: elements that belong to set A but not to set B

B's difference set: elements that belong to the B set but not the A set

 = function(arr) {
  if((arr) === "[object Array]") {
    var interArr = (this, arr);// Intersection array    return (function(v){
      return (v) === -1
    })
  }
}
//How to usevar arr = [1,2,3,4];
([2,4]); // [1,3]

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.