How to remove all the elements from a set in javascript?

JavascriptObject Oriented ProgrammingProgramming

The Set class in JavaScript provides a clear method to remove all elements from a given set object. This method can be used as follows −

Example

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1);
mySet.add(3);
mySet.add("a");
console.log(mySet)
mySet.clear();
console.log(mySet)

Output

Set { 1, 2, 3, 'a' }
Set { }

You can also individually remove the elements by iterating over them.

Example

let mySet = new Set();
mySet.add(1);
mySet.add(2);
mySet.add(1);
mySet.add(3);
mySet.add("a");
console.log(mySet)
for(let i of mySet) {
   console.log(i)
   mySet.delete(i)
}
console.log(mySet)

Output

Set { 1, 2, 3, 'a' }
Set { }
raja
Published on 18-Sep-2019 12:03:47
Advertisements