Remove elements from a Set using Javascript



The delete method checks if a value already exists in the set, if it does, then it removes that value from the set. We can implement it as follows &minusl 

Example

delete(val) {    if (this.has(val)) {       delete this.container[val];       return true;    }    return false; }

You can test this using − 

Example

const testSet = new MySet(); testSet.add(1); testSet.add(2); testSet.add(5); testSet.delete(5); testSet.delete(2); testSet.display(); console.log(testSet.has(5)); console.log(testSet.has(20)); console.log(testSet.has(1));

Output

This will give the output −

{ '1': 1} False False True

In ES6, you use the delete function as follows − 

Example

const testSet = new MySet(); testSet.add(1); testSet.add(2); testSet.add(5); testSet.delete(5); console.log(testSet.has(5)); console.log(testSet.has(20)); console.log(testSet.has(1));

Output

This will give the output −

False False True
Updated on: 2020-06-15T09:42:29+05:30

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements