Add values to a Set in JavaScript
This post will discuss how to add values to a Set in JavaScript.
There are several ways to add values to a set in JavaScript. A set is a data structure that stores unique values of any type. To add values to a set, we can use the following functions:
1. Using Set.add() function
This is the simplest and most common way to add values to a set. The Set.add() function inserts a new element with a specified value into the set, if there is not an element with the same value already in the set. We can pass the value to the add() function as an argument and chain multiple calls to add to insert multiple values. The function chaining works since the add() function returns the set object itself. For instance:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// Create a new set using the Set constructor var mySet = new Set(); // Add some values to the set using the add function mySet.add(1); // chainable mySet.add(5).add("some text"); // The set now contains the added values // Set { 1, 5, 'some text' } console.log(mySet); |
The Array.forEach() function executes a callback function for each element of an array. We can use this function to add each element of an array to an existing set using the Set.add() function. For instance:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
// Create an array const arr = [11, 12, 13, 14, 15]; // Create a set const mySet = new Set([1, 2, 3, 4, 5]); // Add each element of the array to the set using forEach arr.forEach(item => mySet.add(item)); // Log the set // Set(10) { 1, 2, 3, 4, 5, 11, 12, 13, 14, 15 } console.log(mySet); |
2. Using Set Constructor
We can also create a set from an array or any other iterable object, such as a string, a map, or another set. We need to pass the array or the iterable object to the Set() constructor, which creates a new set from the values of the iterable object. This will automatically add all the unique values from the iterable object to the set. We can also use the spread operator (…) to create a new set from an existing array or an existing set or both. For instance:
|
1 2 3 4 5 6 7 8 9 10 11 |
// Pass an array to the Set constructor var mySet = new Set([1, 5]); // Create a new array with some values var myArray = [10, 15, 20]; // Create a new set with the added values using the Set constructor var myNewSet = new Set([...mySet, ...myArray]); // The new set now contains the added values console.log(myNewSet); // Set { 1, 5, 10, 15, 20 } |
That’s all about adding values to a Set in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)