Subtract two Sets in Javascript


The difference of 2 sets means the set being subtracted should have all its elements removed from the set it is being subtracted from. So we can iterate over the second set and remove all the elements present in it from the first set. 

Example

static difference(s1, s2) {
   if (!s1 instanceof MySet || !s2 instanceof MySet) {
      console.log("The given objects are not of type MySet");
      return null;
   }
   let newSet = new MySet();
   s1.forEach(elem => newSet.add(elem));
   s2.forEach(elem => newSet.delete(elem));
   return newSet;
}

You can test this using − 

Example

const testSet1 = new MySet();
testSet1.add(1);
testSet1.add(2);

const testSet2 = new MySet();
testSet2.add(2);
testSet2.add(5);

let testSet3 = MySet.differnce(testSet1, testSet2);
testSet3.display();

Output

This will give the output −

{ '1': 1 }

Note that the difference function is not there in the ES6 API as well. You can make this function be available in the Set class as follows −

Example

Set.difference = function(s1, s2) {
   if (!s1 instanceof Set || !s2 instanceof Set) {
      console.log("The given objects are not of type Set");
      return null;
   }
   let newSet = new Set();
   s1.forEach(elem => newSet.add(elem));
   s2.forEach(elem => newSet.delete(elem));
   return newSet;
}

You can test this using −

Example

let setA = new Set([1, 2, 3, 4]);
let setB = new Set([2, 3]);
console.log(Set.difference(setA, setB));

Output

This will give the output −

Set { 1, 4 }

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 15-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements