Leander Leo Lagardo
Leander Leo Lagardo

Reputation: 91

Delete an item from a JavaScript set

How to delete an item from a set with condition

if(item.id === 2){
   mySet.delete(item)
}

I can't use mySet.has(item) because only common thing in the objects is the id.

Upvotes: 1

Views: 3665

Answers (4)

kimchirichie
kimchirichie

Reputation: 15

similar immutable way to do this in one line:

const result = mySet.filter(x => x.id === 2);

Upvotes: -1

Wyck
Wyck

Reputation: 11750

You can use a for ... of statement to locate and delete matching items from a set according to your conditions. And in case you are concerned, it's ok to delete an item from a set while iterating.

let mySet = new Set([
  { id: 1 },
  { id: 2 },
  { id: 3 }
]);

for (const item of mySet) if (item.id == 2) { mySet.delete(item); /*optional*/ break; }
console.log([...mySet]);

If there are multiple matching items, you can omit the break in this example.

Upvotes: 0

You can create array of remaining items like

var resultArr = [];    
yourobj.forEach((item,index)=>{ 
        if(item.id === 2)
        {
          // nothing
        }  
        else
        {
            resultArr.push(item);
        }
})

Upvotes: 2

CertainPerformance
CertainPerformance

Reputation: 370989

Unless you already have a reference to the object, you'll have to iterate through the Set's values to .find the matching object, then call .delete with it:

const set = new Set([
  { id: 1 },
  { id: 2 },
]);

const obj = [...set].find(obj => obj.id === 2);
set.delete(obj);
console.log([...set]);

Upvotes: 3

Related Questions