Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an object from a Set in JavaScript

Tags:

javascript

set

I would appreciate assistance regarding how to remove/delete a specific object from a Set in JavaScript. I have not been able to find the answer to this seemingly simple question online. Please see the following simple example Set:

let mySet = new Set([1, 2, {Name: "Ann"}]);

Set(3) {1, 2, {…}}



mySet.delete(1);  

console.log(mySet);

Set(2) {2, {…}}

// The basic syntax above doesn't seem to delete an object within a Set. I have tried the following, none of which removed the object:

mySet.delete({"Name": "Ann"});
false

mySet.delete("Name");
false

mySet.delete("Ann");
false

Is there a different approach that will remove a specific object from a Set in JavaScript? Perhaps a for...of loop, but then how to specify the specific object for removal? Any help would be greatly appreciated. :)

like image 314
Chess Avatar asked Aug 30 '26 23:08

Chess


1 Answers

The Set object lets you store unique values of any type, whether primitive values or object references.

So this will simply add 2 objects to Set since they do not have the same object references.

var mySet = new Set([{Name: "Ann"}, {Name: "Ann"}]);

console.log(mySet.size) // 2

You might as well use an array in this case.

So in this scenario to remove Ann (since we do not have an object reference) we would have to:

var mySet = new Set([1, 2, "abc", {Name: "Ann"}]);

console.log('With Ann size:', mySet.size)

mySet.forEach(x => x.Name === 'Ann' ? mySet.delete(x) : x)

console.log('Bye Ann size:', mySet.size)

Now consider this:

var ann = {Name: 'Ann'}
var mySet = new Set([ann, ann])

console.log('With Ann size:', mySet.size)

mySet.delete(ann)

console.log('Bye Ann size:', mySet.size)

So as you can see we are now dealing with object references and firstly the size is only 1 and the Set can now find ann reference and remove it with no issues.

like image 155
Akrion Avatar answered Sep 01 '26 16:09

Akrion