How to Remove an Element from a Set in JavaScript ?
To remove an element from a Set in JavaScript, you can use the delete()
method. The delete()
method removes the specified element from the Set if it exists and returns a boolean indicating whether the element was successfully deleted.
Example: Here, the delete(3)
method call removes the element 3
from the Set. The second console.log
shows the updated Set without the deleted element.
Javascript
let mySet = new Set([1, 2, 3, 4, 5]); console.log(mySet); // Output: Set { 1, 2, 3, 4, 5 } // Remove element 3 from the Set mySet. delete (3); console.log(mySet); // Output: Set { 1, 2, 4, 5 } |
Output
Set(5) { 1, 2, 3, 4, 5 } Set(4) { 1, 2, 4, 5 }
Note: It’s important to note that if the element is not present in the Set, the delete()
method will return false
.