Add An Array Of Values To An Existing Set In JavaScript

To add an array of values to an existing set in JavaScript, you can use any of the following methods –

  1. Use the forEach() method to iterate over the array and add each element to the set.
  2. Use the spread operator to add the array of values to the existing set.
  3. Use the for-of loop to iterate over the array and add each element to the set.

Let’s discuss each of these methods in detail below.

Add An Array Of Values To An Existing Set In JavaScript

add an array of values to an existing set in javascript

Use The forEach() Method

The forEach() method accepts a callback function as an argument and calls that function once for each element in the array.

You can use the forEach() method to add an array of values to an existing set as follows –

let myArray = [‘a’, ‘b’, ‘c’];

let mySet = new Set([‘x’, ‘y’, ‘z’]);

myArray.forEach(element => mySet.add(element));

console.log(mySet);

// Output – Set { ‘x’, ‘y’, ‘z’, ‘a’, ‘b’, ‘c’ }

In the above code, we have first created an array myArray with some elements. We have also created a Set named mySet with some values.

Next, we have used the forEach() method to iterate over the array and add each element to the set. Finally, we have printed the updated set in the console.

Use The Spread Operator

The spread operator can be used to add the elements of an array to an existing set as follows –

let myArray = [‘a’, ‘b’, ‘c’];

let mySet = new Set([‘x’, ‘y’, ‘z’]);

mySet = new Set([...mySet, ...myArray]);

console.log(mySet);

// Output – Set { ‘x’, ‘y’, ‘z’, ‘a’, ‘b’, ‘c’ }

In the above code, we have first created an array myArray with some elements. We have also created a Set named mySet with some values.

Next, we have used the spread operator to add the contents of both myArray and mySet to a new Set. Finally, we have printed the updated set in the console.

Use The for-of Loop

The for-of loop can be used to iterate over the elements of an array and add them to an existing set as follows –

let myArray = [‘a’, ‘b’, ‘c’];

let mySet = new Set([‘x’, ‘y’, ‘z’]);

for (const element of myArray) {

  mySet.add(element);

}

console.log(mySet);

// Output – Set { ‘x’, ‘y’, ‘z’, ‘a’, ‘b’, ‘c’ }

As you can see, using the for-of loop is very similar to using the forEach() method. The only difference is that we have used the for-of loop instead of the forEach() method.

You can use any of the above methods to add an array of values to an existing set in JavaScript. Pick the method that you find most convenient to use in your situation.

I hope this article was helpful and that you were able to learn something new from it. If you have any questions or comments, please feel free to leave them below.

Happy coding! 🙂

Leave a Reply