You have to use the delete method to remove the element form set in JavaScript. This method removes a specified value from a Set
object, if it is in the set.
setObj.delete()
If the value exists in the Set
, it gets removed from the Set
object and true
is returned, otherwise the method returns false
.
JavaScript Set remove
Simple example code passes the value to delete from the set.
<!DOCTYPE html>
<html>
<body>
<script>
const s = new Set([1,2,3,4]);
console.log(s.delete(1))
console.log(s.delete(5))
console.log(s)
</script>
</body>
</html>
Output:
If you need to delete an object or array from a Set
, you need to have a reference to the object / array, or use the forEach
method to get a reference.
const set1 = new Set([{id: 1}, {id: 2}]);
set1.forEach(obj => {
if (obj.id === 2) {
set1.delete(obj);
}
});
console.log(set1); // 👉️ { {id: 1} }
If you have a direct reference to the object, there’s an easier way to do this.
const obj = {id: 1};
const set1 = new Set([obj, {id: 2}]);
set1.delete(obj);
console.log(set1); // 👉️ { {id: 2} }
Do comment if you have any doubts or suggestions on this Js modifying set topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version