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



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 { }
Updated on: 2019-09-18T12:03:47+05:30

462 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements