Search code examples
javascriptarraysunionintersectionset-theory

Performing Set calculations in javascript array


I have 2 arrays lets say:

A = [1,2,3,4,5] and B = [1,2,3,6,7]

and I'd like to perform the following 'set calculations':

C = (A ∩ B)
D = A - (A ∩ B)
E = B - (A ∩ B)

Essentially:

C = [1,2,3]
D = [4,5]
E = [6,7]

Is there a smart way to do this or am I going to have to cross check each array member with loops and ifs? I cannot use an external library (like math.js or w/e).

Thanks in advance.


Solution

  • filter() can at least hide the loops for you:

    A = [1,2,3,4,5];
    B = [1,2,3,6,7];
    
    C = intersection(A, B);
    D = arrayDiff(A, C);
    E = arrayDiff(B, C);
    
    console.log(JSON.stringify(C));
    console.log(JSON.stringify(D));
    console.log(JSON.stringify(E));
    
    function intersection(a, b) {
      return a.filter( 
        function(el) {
          return b.indexOf(el) >= 0;
        }
      );
    }
    
    function arrayDiff(a, b) {
      return a.filter( 
        function(el) {
          return b.indexOf(el) < 0;
        }
      );
    }