Insert all array elements into a set in JavaScript
This post will discuss how to insert the elements of an array to a set in JavaScript.
A set is a collection of unique values that can be any type of data, and an array is a list-like object that can store multiple values of any type. Here are some of the functions that we can use to insert the contents of an array to a set in JavaScript:
1. Using for…of loop
We can use a for…of loop to iterate over the array and use the Set.add() function to add each element to the set. This function returns the set object itself, so we can chain multiple calls if we want. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
// create an empty set let mySet = new Set(); // create an array with some values let myArray = [1, 2, 3, 3, 4]; for (let item of myArray) { // add each item to the set mySet.add(item); } console.log(mySet); // Set(4) {1, 2, 3, 4} |
2. Using spread operator
We can use the spread operator (…) to expand the elements of the array into individual arguments and pass them to the Set constructor. This will create a new set with the unique values from the array. We can also use this function to merge an existing set with an array. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// create an array with some values let myArray = [1, 2, 3, 3, 4]; // create a new set with the unique values from the array let mySet = new Set(myArray); console.log(mySet); // Set(4) {1, 2, 3, 4} // create another set with some values let anotherSet = new Set([5, 6, 7]); // create a new set by merging the existing set and the array let mergedSet = new Set([...mySet, ...anotherSet]); console.log(mergedSet); // Set(7) {1, 2, 3, 4, 5, 6, 7} |
3. Using Array.forEach() function
We can use the Array.forEach() function to execute a function for each element of the array and use the Set.add() function inside the function to add each element to the set. This function does not return anything, but modifies the original set. Here’s an example:
|
1 2 3 4 5 6 7 8 9 10 |
// create an empty set let mySet = new Set(); // create an array with some values let myArray = [1, 2, 3, 3, 4]; // execute a function for each item and add it to the set myArray.forEach(item => mySet.add(item)); console.log(mySet); // Set(4) {1, 2, 3, 4} |
All functions achieve the same result of inserting the elements of an array to a set. Choose the one that suits the needs and coding style. That’s all about adding the contents of an array 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 :)