Skip to main content

How to Remove an Element from a Set in JavaScript

A Set in JavaScript is a collection of unique values. A common operation is to remove an element from a Set after it has been added. The primary method for this is Set.prototype.delete(), but its behavior differs crucially depending on whether you are removing a primitive value (like a string or number) or an object.

This guide will teach you how to correctly use the delete() method for both primitives and objects, highlight the common "gotcha" related to object references, and show you how to reliably find and remove an object from a Set.

The Core Method: Set.prototype.delete()

The delete() method is the standard way to remove an element from a Set. It searches for the specified value, removes it if found, and returns a boolean indicating if the element was successfully removed.

  • It returns true if the element existed and was removed.
  • It returns false if the element did not exist in the Set.
const mySet = new Set(['apple', 'banana', 'cherry']);

const wasRemoved = mySet.delete('banana');

console.log(mySet); // Output: Set(2) { 'apple', 'cherry' }
console.log(wasRemoved); // Output: true

const wasRemovedAgain = mySet.delete('grape'); // 'grape' does not exist
console.log(wasRemovedAgain); // Output: false
note

The delete() method modifies the Set in place.

The Critical Distinction: Primitives vs. Objects

This is the most important concept to understand when using Set.delete().

  • Primitives (strings, numbers, booleans): Are compared by their value. delete('apple') works because the Set looks for a string with the value "apple".
  • Objects (including arrays): Are compared by their reference. The Set looks for the exact same object in memory, not just an object with the same properties.

For example, trying to delete an object by creating a "new" one with identical properties will fail.

// Problem: Why doesn't this work?
const userSet = new Set([{ id: 1, name: 'Alice' }]);

// This creates a NEW object, which has a different memory reference.
const wasRemoved = userSet.delete({ id: 1, name: 'Alice' });

console.log(wasRemoved); // Output: false
console.log(userSet.size); // Output: 1 (The object was not removed)
note

The Set does not contain the new object you tried to delete; it contains the original object.

Removing a Primitive Value (The Simple Case)

Because primitives are compared by value, removing them is straightforward.

const colors = new Set(['red', 'green', 'blue']);

// Simply provide the value you want to remove.
colors.delete('green');

console.log(colors.has('green')); // Output: false
console.log(colors); // Output: Set(2) { 'red', 'blue' }

Removing an Object (The Tricky Case)

To delete an object, you must have a reference to the exact object that is stored in the Set. There are two common scenarios for this.

By Direct Reference

If you still have a variable that points to the object you want to delete, you can use it directly.

Solution:

const userAlice = { id: 1, name: 'Alice' };
const userBob = { id: 2, name: 'Bob' };
const userSet = new Set([userAlice, userBob]);

// We have a direct reference to userAlice, so we can delete it.
userSet.delete(userAlice);

console.log(userSet.has(userAlice)); // Output: false
console.log(userSet); // Output: Set(1) { { id: 2, name: 'Bob' } }

By Finding the Object in the Set

More often, you won't have a direct reference, but you will know a unique property of the object you want to remove (like an ID). In this case, you must first iterate over the Set to find the object and get its reference.

Solution:

const userSet = new Set([
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' },
{ id: 3, name: 'Charlie' }
]);

const idToDelete = 2;

for (const user of userSet) {
if (user.id === idToDelete) {
userSet.delete(user);
break; // Exit the loop once the object is found and deleted
}
}

console.log(userSet);
// Output: Set(2) { { id: 1, name: 'Alice' }, { id: 3, name: 'Charlie' } }

Practical Example: A User Management List

This example simulates a simple service for managing a list of active users, demonstrating how to add a user and then remove them by their ID.

class ActiveUsers {
constructor() {
this.users = new Set();
}

addUser(user) {
this.users.add(user);
console.log(`${user.name} added.`);
}

removeUserById(userId) {
let userToDelete = null;
for (const user of this.users) {
if (user.id === userId) {
userToDelete = user;
break;
}
}

if (userToDelete) {
this.users.delete(userToDelete);
console.log(`User with ID ${userId} removed.`);
} else {
console.log(`User with ID ${userId} not found.`);
}
}
}

const userList = new ActiveUsers();
const alice = { id: 101, name: 'Alice' };
const bob = { id: 102, name: 'Bob' };

userList.addUser(alice); // Alice added.
userList.addUser(bob); // Bob added.
console.log(userList.users.size); // Output: 2

userList.removeUserById(101); // User with ID 101 removed.
console.log(userList.users.size); // Output: 1

Conclusion

The Set.prototype.delete() method is the standard way to remove elements from a Set.

  • For primitive values (strings, numbers), the process is straightforward: set.delete(value).
  • For objects, you cannot create a "new" object to delete an old one. You must have a reference to the exact object you wish to remove.
  • If you don't have a direct reference, you must first iterate over the Set to find the object based on one of its unique properties, and then use that reference in the delete() method.