- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 Articles
- Adding two Sets in Javascript
- Cartesian product of two sets in JavaScript
- Finding union of two sets in JavaScript
- Explain sets in JavaScript?
- Merge two sets in Java
- What are javascript sets?
- When should you use sets in Javascript?
- Java Program to compare two sets
- Get the intersection of two sets in Java
- Get the union of two sets in Java
- C# Program to Subtract Two TimeSpan
- Java program to subtract two matrices.
- Check if two given sets are disjoint?
- Get the asymmetric difference of two sets in Java
- 8085 program to subtract two BCD numbers

Advertisements