
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
- Related Questions & Answers
- Adding two Sets in Javascript
- Cartesian product of two sets in JavaScript
- Finding union of two sets in JavaScript
- Merge two sets in Java
- Explain sets in JavaScript?
- Java Program to compare two sets
- What are javascript sets?
- Java program to subtract two matrices.
- C# Program to Subtract Two TimeSpan
- Get the intersection of two sets in Java
- Get the union of two sets in Java
- Check if two given sets are disjoint?
- 8085 program to subtract two BCD numbers
- Get the asymmetric difference of two sets in Java
- Java Program to Calculate union of two sets
Advertisements