JavaScript – Delete an Element from Set

To delete an element from Set in JavaScript, call delete() method on this set and pass the specific element as argument to it.

delete() method returns a boolean value. The return value is true if the key is successfully removed from the set, else, false.

Syntax

The syntax to remove/delete a specific element e from a Set set1 using delete() method is

</>
Copy
set1.delete(e)

Examples

In the following example, we take a Set set1 with three elements. We shall delete the element 'banana' using delete() method.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var set1 = new Set(['apple', 'banana', 'orange']);
        var result = set1.delete('banana');

        var displayOutput = 'Is the element removed? ' + result + '\n\n';
        displayOutput += 'Set elements after delete() :\n'
        set1.forEach (function(element) {
            displayOutput += element + '\n';
        });
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

If the specified element is not present, then delete() method does nothing and returns false.

In the following example, we try to delete an element 'cherry' which is not present in the Set set1.

index.html

<!DOCTYPE html>
<html lang="en">
<body>
    <pre id="output"></pre>
    <script>
        var set1 = new Set(['apple', 'banana', 'orange']);
        var result = set1.delete('cherry');

        var displayOutput = 'Is the element removed? ' + result + '\n\n';
        displayOutput += 'Set elements after delete() :\n'
        set1.forEach (function(element) {
            displayOutput += element + '\n';
        });
        document.getElementById('output').innerHTML += displayOutput;
    </script>
</body>
</html>

Conclusion

In this JavaScript Tutorial, we learned how to delete a specific element from a Set in JavaScript using delete() method, with examples.