Performing Set calculations in javascript array

1.4k views Asked by At

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.

2

There are 2 answers

1
Paul Roub On BEST ANSWER

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;
    }
  );
}

1
daramcq On

As of ES6, Javascript has an inbuilt set object, which offers neat ways to do the above operations.

var intersection = (setA, setB) => new Set([...setA].filter(x => setB.has(x)));

var difference = (setA, setB) => new Set([...setA].filter(x => !setB.has(x)));

A = new Set([1,2,3,4,5]);
B = new Set([1,2,3,6,7]);

// A ∩ B = ([1,2,3])
console.log(intersection(A, B));

// A \ B = ([4,5])
console.log(difference(A, B));

// B \ A = ([6,7])
console.log(difference(B, A));