How to Remove an Element from a Set using JavaScript

avatar

Borislav Hadzhiev

Thu Oct 28 20212 min read

banner

Photo by João Ferrão

Remove an Element from a Set #

To remove an element from a Set, call the delete() method, passing it the value as a parameter. If the value exists in the Set, it gets removed from the Set object and true is returned, otherwise the method returns false.

index.js
const set1 = new Set(['one', 'two', 'three']); set1.delete('two'); console.log(set1); // 👉️ {'one', 'three'} console.log(set1.has('two')); // 👉️ false
If you need to remove an object or array element from a Set, scroll down to the next section.

We used the Set.delete method to remove an element from a Set.

The only parameter the method takes is tha value we want to remove.

The delete method returns true if the value was in the Set and false otherwise.

index.js
const set1 = new Set(['one', 'two', 'three']); console.log(set1.delete('two')); // 👉️ true console.log(set1.delete('four')); // 👉️ false

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.

index.js
const set1 = new Set([{id: 1}, {id: 2}]); console.log(set1); // 👉️ {{id: 1}, {id: 2}} set1.forEach(obj => { if (obj.id === 2) { set1.delete(obj); } }); console.log(set1); // 👉️ { {id: 1} }

We used the Set.forEach method to iterate over the Set and get a reference to the object we wanted to delete.

The function we passed to the forEach method gets called with each element in the Set, so we can conditionally check if the current object is the one we want to delete.

If you have a direct reference to the object, there's an easier way to do this.

index.js
const obj = {id: 1}; const set1 = new Set([obj, {id: 2}]); set1.delete(obj); console.log(set1); // 👉️ { {id: 2} }

In most situations, you will not have a direct reference to the object / array you're trying to remove from the Set, so using the forEach method is a great alternative.

Further Reading #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee