2

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
  • Since you cannot use an external library, it seems you are going to have to depend on lots of raw for-loops or writing a small library of your own. Either way, you'll be using for-loops. Hopefully, this isn't homework. Commented Dec 23, 2014 at 15:22
  • No this isn't homework it is work related and I do not want to add a whole external library into our SVN project just for 3 lines of code. I can think of ways to get the result I want I just thought of asking here for a more elegant solution. Also I haven't had the need to use set theory with arrays before so I thought it would be a good idea to learn some stuff here for later use. Commented Dec 24, 2014 at 8:15

2 Answers 2

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

It's times like these that I appreciate being proved wrong.
2

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

1 Comment

this is not valid JavaScript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.