Christopher Bradshaw
Christopher Bradshaw

Reputation: 2773

How do I change the value of an item in a Set?

I have a Set that I want to update in JavaScript, but I can't figure out anything that lets me update values within it.

const mySet = new Set([]);
mySet.add('hello');
mySet.add('hewwo');
mySet.add('henlo');

I've tried syntax like

mySet['hello'] = 'hello world',

mySet.hello = 'hello world', and

mySet[0] = 'hello world'.

I've also tried modifying the value like this:

mySet.forEach(item => {
  if (item === 'hello') {
    item = 'hello world';
  }
})

Nothing has worked for me so far though. I wanted to use a set over a normal array because it prevents duplicate items automatically, but should I just add the logic myself? Is there a good use case for sets in JavaScript if I can't modify the values in them?

Upvotes: 4

Views: 13659

Answers (4)

bloodedark
bloodedark

Reputation: 103

I had a set and I wanted to update values that may contains duplicate during update. This is what I did

let test = new Set([1,2,3]);
let tmpSet = new Set();
for (let num of test) {
    tmpSet.add(num+1);
    
}
test = tmpSet;
console.log(tmpSet); // [2,3,4]

Upvotes: 0

Code Maniac
Code Maniac

Reputation: 37755

In Set you need to delete the previously available value and than add new one if you want to replace already existing value,

One alternative when you want to replace key's value regularly you can use Map

const myMap = new Map([]);
myMap.set('hello', 'hello');
myMap.set('hewwo', 'hewwo');
myMap.set('hello', 'Hello world')

console.log([...myMap.values()].join('\n')); 

// join('\n') is just for formatting output

Upvotes: 3

User863
User863

Reputation: 20039

The Set lets you store unique values

For specified key and a value pairs use Map

const myMap = new Map();
myMap.set('hello', 'hello');
myMap.set('hewwo', 'hewwo');
myMap.set('henlo', 'henlo');

myMap.set('hello', 'hello world');

console.log(myMap.get('hello'))

console.log(...myMap.entries())

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371019

The only way to "modify" a (primitive) item would be to remove it from the Set and then add the altered item.

const mySet = new Set([]);
mySet.add('hello');
mySet.add('hewwo');
mySet.add('henlo');

if (mySet.has('hello')) {
  mySet.delete('hello');
  mySet.add('hello world');
}

console.log(...mySet);

If you want to change each item, either iterate over each item, deleting and adding again, or (as would probably be easier) transform it into an array and .map into a new Set.

While you can do this, it's still a pretty weird thing to want to do. It's useful to think of Sets as unordered collections, which can have values individually added or removed.

One big reason sets are useful is that looking up values in them is an O(1) operation, unlike with arrays (where lookup requires O(n) time).

Upvotes: 8

Related Questions