Skip to content

JavaScript set delete() | Method

  • by

The JavaScript Set delete() method is used to remove the elements from the Set object. You can remove a specified value from a Set object, if it is in the set by passing value into the method.

setObj.delete()

// or use for single value
set.delete(value)

JavaScript set delete

Simple example code delete any point with x > 10.

<!DOCTYPE html>
<html>
<body>
  <script>
    const set1 = new Set([1,20,3,40]);

    // Delete any point with `x > 10`.
    set1.forEach((point) => {
      if (point > 10) {
        set1.delete(point);
      }
    });

    console.log(set1);

  </script>
</body>
</html>

Output:

JavaScript set delete() Method

Remove a set of values in an existing Set

It is much easier to write your own function than using a library for a single lightweight functionality:

var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);

function removeAll(originalSet, toBeRemovedSet) {
  [...toBeRemovedSet].forEach(function(v) {
    originalSet.delete(v); 
  });
}

console.log([...mySet]);
removeAll(mySet, valuesToRemove);
console.log([...mySet]);

You could use Set#forEach directly with the set and delete then the value from the other set.

var mySet = new Set(["foo", "bar", "baz"]);
var valuesToRemove = new Set(["foo", "baz"]);

function removeAll(originalSet, toBeRemovedSet) {
    toBeRemovedSet.forEach(Set.prototype.delete, originalSet);
}

console.log([...mySet]);
removeAll(mySet, valuesToRemove);
console.log([...mySet]);

Deleting an object from a set

const setObj = new Set(); // Create a new set.

setObj.add({ x: 10, y: 20 }); // Add object in the set.

setObj.add({ x: 20, y: 30 }); // Add object in the set.

// Delete any point with `x > 10`.
setObj.forEach((point) => {
  if (point.x > 10) {
    setObj.delete(point);
  }
});

Do comment if you have any doubts or suggestions on this Js set method topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading