How to Remove an Element from a Set using JavaScript

avatar

Borislav Hadzhiev

2 min

banner

Photo from Unsplash

Remove an Element from a Set in JavaScript #

Use the Set.delete() method to remove an element from a Set, e.g. set.delete('element').

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(['bobby', 'hadz', 'com']); set1.delete('hadz'); console.log(set1); // ๐Ÿ‘‰๏ธ Set(2) { 'bobby', 'com' } console.log(set1.has('hadz')); // ๐Ÿ‘‰๏ธ false

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

The only parameter the method takes is the 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(); set1.add('bobby'); set1.add('hadz'); set1.add('com'); console.log(set1); // ๐Ÿ‘‰๏ธ Set(3) { 'bobby', 'hadz', 'com' } console.log(set1.delete('bobby')); // ๐Ÿ‘‰๏ธ true console.log(set1.delete('asdf')); // ๐Ÿ‘‰๏ธ false

Remove an Object or Array from a Set object in JavaScript #

If you need to delete an object or array from a Set, you need to have a reference to the object or 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.

On each iteration, we check if the current object is the one we want to delete.

There's an easier way to do this if you have a direct reference to the object.

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 or array you're trying to remove from the Set, so using the forEach() method is a great alternative.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2023 Borislav Hadzhiev