In this article we will learn how to update an element in a set.
It is very common to update an element in a set in JavaScript.
Problem
Now we have a problem, which is that we want to update the value in the set
Imagine we have a set like this:
// set
const set = new Set([1, 2, 3, 4]);
console.log(set);
// Set(4) { 1, 2, 3, 4 }
And we want to update these values to become like this:
Set(4) { 10, 20, 30, 44 }
How to solve this problem?
Unfortunately, there is no built-in function that modifies those values in Set.
So we will convert the Set into an array and then modify the values in the array and return them back to Set.
The solution will be as follows
- Convert set to an array using
Array.from
method - Modify elements in array
- Convert an array to set again using
new Set(arr)
.
Update elements in a set
// Set
const set = new Set([1, 2, 3, 4]);
// Convert set to an array
const toArray = Array.from(set);
// Update values
toArray[0] = 10;
toArray[1] = 20;
toArray[2] = 30;
toArray[3] = 40;
// Convert an array to set
const result = new Set(toArray);
// Result:
console.log(result);
Output
Set(4) { 10, 20, 30, 40 }
Thank you for reading
Thank you for reading my blog. 🚀