In this lab, we explore Sets, a unique data structure in JavaScript introduced with ES6. Unlike arrays, Sets store only unique values and are ideal for scenarios where duplicate values need to be avoided. This exercise will help you understand how to create and manipulate Sets, including adding, deleting, and checking for values.
- Sets: Learn to initialize Sets and enforce uniqueness.
- Set Methods: Use methods to add, delete, check for values, and clear Sets.
- Conversions and Iterations: Practice converting between Sets and arrays and iterating over Sets.
- Be able to use Sets to manage unique data.
- Convert between arrays and Sets to leverage the unique properties of each.
- Gain practice with Set-specific methods for efficient data handling.
Your project should be structured as follows:
javascript-sets/
├── index.js
└── README.md
-
Create a project folder named javascript-sets to store your project files.
-
Inside the javascript-sets folder, create a file named index.js. This will be your main JavaScript file where all your code will be written.
Now that you have created the index.js
file, let's start by initializing a Set
and displaying its initial state.
-
Open the
index.js
file in thejavascript-sets
folder and add the following code to set up aSet
and log it to the console.// Working with Sets: Declare the set before using it const uniqueNames = new Set(); // Display the empty Set console.log("Initial uniqueNames Set:", uniqueNames);
-
Run your code using Node.js in the terminal:
node index.js
Initial uniqueNames Set: Set(0) {}
Explanation:
Initialization:
- The line
const uniqueNames = new Set();
initializes an emptySet
nameduniqueNames
. ThisSet
will hold only unique values, ensuring that no duplicates are stored.
Displaying the Set:
- The line
console.log("Initial uniqueNames Set:", uniqueNames);
logs the initial state of theuniqueNames
Set to the console. - The output shows
Set(0) {}
, whereSet(0)
indicates that the Set is empty and has0
elements at this stage. The curly braces{}
show that there are no values currently stored in theSet
. This confirms that theSet
has been created but contains no elements yet.
Now that the uniqueNames
Set has been created and initialized, let's add some values to it.
-
Open the
index.js
file in thejavascript-sets
folder and add the following code to populate theuniqueNames
Set with initial values and log the updated Set to the console.// Adding values to the Set uniqueNames.add("David"); uniqueNames.add("Sarah"); uniqueNames.add("John"); // Display the Set after adding values console.log("uniqueNames after adding values:", uniqueNames);
-
Run your code using Node.js in the terminal:
node index.js
uniqueNames after adding values: Set(3) { 'David', 'Sarah', 'John' }
Explanation:
Adding Values:
- The
add
method is used to add values to the Set:uniqueNames.add("David");
adds the value"David"
to the Set.uniqueNames.add("Sarah");
adds the value"Sarah"
to the Set.uniqueNames.add("John");
adds the value"John"
to the Set.
- Each value is added uniquely; if a duplicate value is added, it will not be stored again in the Set.
Displaying the Updated Set:
- The line
console.log("uniqueNames after adding values:", uniqueNames);
logs the updated state of theuniqueNames
Set to the console. - The expected output shows
Set(3) { 'David', 'Sarah', 'John' }
, whereSet(3)
indicates that the Set now contains3
unique elements. The curly braces{}
list the elements in the Set, confirming that the values"David"
,"Sarah"
, and"John"
have been added successfully.
Let's test what happens when we attempt to add a duplicate value to the uniqueNames
Set, and then log the Set's size to confirm it only stores unique values.
-
In the
index.js
file, add the following code to add a duplicate value and check the size of the Set.// Attempting to add duplicate values uniqueNames.add("David"); console.log("uniqueNames after attempting to add 'David' again:", uniqueNames); // Checking the size of the Set console.log("Size of uniqueNames Set:", uniqueNames.size);
-
Run your code using Node.js in the terminal:
node index.js
uniqueNames after attempting to add 'David' again: Set(3) { 'David', 'Sarah', 'John' }
Size of uniqueNames Set: 3
Explanation:
Adding a Duplicate Value:
- The line
uniqueNames.add("David");
attempts to add the value"David"
to theuniqueNames
Set again. - Sets in JavaScript only store unique values, so attempting to add
"David"
a second time does not change the contents of the Set. This helps enforce uniqueness, as the Set automatically disregards duplicate entries.
Displaying the Updated Set:
- The line
console.log("uniqueNames after attempting to add 'David' again:", uniqueNames);
logs the state of theuniqueNames
Set after attempting to add a duplicate value. - The output
Set(3) { 'David', 'Sarah', 'John' }
shows that the Set still contains only three unique elements, with no duplicate"David"
added.
Checking the Size:
- The line
console.log("Size of uniqueNames Set:", uniqueNames.size);
logs the current size of the Set. - The output
Size of uniqueNames Set: 3
confirms that the Set has a total of three unique elements, verifying that duplicate entries are not counted.
In this step, we’ll remove a value from the uniqueNames
Set, check for the presence of specific values, and finally clear the Set completely.
-
In the
index.js
file, add the following code to delete a value, check for values, and then clear the Set.// Deleting a value from the Set uniqueNames.delete("Sarah"); console.log("uniqueNames after deleting 'Sarah':", uniqueNames); // Checking if a value exists in the Set console.log("Does uniqueNames have 'John'?", uniqueNames.has("John")); console.log("Does uniqueNames have 'Sarah'?", uniqueNames.has("Sarah")); // Clearing all values from the Set uniqueNames.clear(); console.log("uniqueNames after clearing all values:", uniqueNames);
-
Run your code using Node.js in the terminal:
node index.js
uniqueNames after deleting 'Sarah': Set(2) { 'David', 'John' }
Does uniqueNames have 'John'? true
Does uniqueNames have 'Sarah'? false
uniqueNames after clearing all values: Set(0) {}
Explanation:
Deleting a Value:
- The
delete
method is used to remove a specific value from the Set:uniqueNames.delete("Sarah");
removes the value"Sarah"
from theuniqueNames
Set.
- The line
console.log("uniqueNames after deleting 'Sarah':", uniqueNames);
logs the Set's updated state, showing that"Sarah"
has been removed and only"David"
and"John"
remain.
Checking for Values:
- The
has
method checks whether a specific value exists in the Set:uniqueNames.has("John")
returnstrue
because"John"
is present in the Set.uniqueNames.has("Sarah")
returnsfalse
because"Sarah"
was removed earlier.
- Logging these checks confirms the presence (or absence) of values in the Set after modifications.
Clearing the Set:
- The
clear
method removes all values from the Set:uniqueNames.clear();
clears every element, making the Set empty.
- The final line
console.log("uniqueNames after clearing all values:", uniqueNames);
logs the empty state of the Set, displayed asSet(0) {}
, verifying that all elements have been successfully removed.
In this step, we’ll create an array containing duplicate values, convert it to a Set to remove duplicates, and then convert it back to an array to view the unique values.
-
In the
index.js
file, add the following code to create an array with duplicates, convert it to a Set, and log the results.// Converting between Sets and Arrays const animalsArray = ["dog", "cat", "dog", "bird", "cat"]; const uniqueAnimals = Array.from(new Set(animalsArray)); // Logging the original and unique arrays console.log(`Animals Array: ${animalsArray}`); // Outputs the full array with duplicates console.log(`UniqueAnimals Array from Set: ${uniqueAnimals}`); // Output: ['dog', 'cat', 'bird']
-
Run your code using Node.js in the terminal:
node index.js
Animals Array: dog,cat,dog,bird,cat
UniqueAnimals Array from Set: dog,cat,bird
Explanation:
Original Array with Duplicates:
- The
animalsArray
is initialized with values that include duplicates:"dog"
,"cat"
,"dog"
,"bird"
, and"cat"
. - When we log
animalsArray
, it shows the array in its original form, complete with duplicate entries.
Converting to a Set to Remove Duplicates:
new Set(animalsArray)
convertsanimalsArray
into a Set, which automatically filters out duplicate values, ensuring only unique elements are stored.- Wrapping this Set in
Array.from()
converts the unique values in the Set back into an array format, resulting inuniqueAnimals
.
Logging the Unique Array:
- The line
console.log("UniqueAnimals Array from Set:", uniqueAnimals);
logs the array created from the Set, showing only unique values. - The output confirms that duplicates have been removed, displaying only
"dog"
,"cat"
, and"bird"
in theuniqueAnimals
array.
Another method to create an array from a Set is by using the spread operator (...
). This approach is concise and achieves the same result of removing duplicates from an array.
-
In the
index.js
file, add the following code to create a unique array using the spread operator.// Another way to create an array from a Set using the spread operator const uniqueAnimalsAlt = [...new Set(animalsArray)]; console.log(`UniqueAnimals Array using spread operator: ${uniqueAnimalsAlt}`);
-
Run your code using Node.js in the terminal:
node index.js
UniqueAnimals Array using spread operator: dog,cat,bird
Explanation:
Using the Spread Operator:
- The spread operator (
...
) is a concise way to create an array from a Set. By using[...new Set(animalsArray)]
, we first convertanimalsArray
into a Set, which removes any duplicate values. - The spread operator then expands the unique elements from the Set into a new array,
uniqueAnimalsAlt
, effectively creating an array with only unique values fromanimalsArray
.
Logging the Unique Array:
- The line
console.log("UniqueAnimals Array using spread operator:", uniqueAnimalsAlt);
logs the array created with the spread operator, showing the unique values. - The output confirms that duplicates are removed, with only unique values
"dog"
,"cat"
, and"bird"
displayed in theuniqueAnimalsAlt
array.
In this step, we’ll create a new Set, log each item using iteration, and then convert the Set back to an array.
-
In the
index.js
file, add the following code to create a Set, iterate through it, and convert it to an array.// Iterating through a Set const fruits = new Set(["apple", "banana", "cherry"]); fruits.forEach((fruit) => console.log("Fruit:", fruit)); // Converting a Set back to an Array const fruitsArray = Array.from(fruits); console.log("Fruits Array from Set:", fruitsArray);
-
Run your code using Node.js in the terminal:
node index.js
Fruit: apple
Fruit: banana
Fruit: cherry
Fruits Array from Set: apple,banana,cherry
Explanation:
Creating and Iterating Through the Set:
- A new Set,
fruits
, is initialized with three unique values:"apple"
,"banana"
, and"cherry"
. - The
forEach
method is used to iterate over each item in thefruits
Set:fruits.forEach((fruit) => console.log("Fruit:", fruit));
logs each value individually. This loop prints each fruit name to the console.
Converting the Set to an Array:
- The line
Array.from(fruits)
converts thefruits
Set to an array,fruitsArray
, containing all unique values from the Set in insertion order. - The line
console.log("Fruits Array from Set:", fruitsArray);
then logs the new array, displaying the converted values as["apple", "banana", "cherry"]
, verifying that the Set was successfully converted back to an array.
In this final step, you’ll commit your changes and push your project to GitHub to save and share your work. This ensures that your project is versioned and backed up remotely.
-
Initialize Git (if not already initialized):
git init
-
Add All Changes to Staging:
git add .
-
Commit Your Changes:
git commit -m "Add code for working with Sets, including conversions and iterations"
-
Connect to Your GitHub Repository (if not already connected):
- Replace
<username>
with your GitHub username and<repository-name>
with the name of your repository.
git remote add origin https://github.com/<username>/<repository-name>.git
- Replace
-
Push to GitHub:
git push -u origin main
In this lab, you learned how to use JavaScript Sets to manage collections of unique values effectively. By following each step, you gained practical experience with:
- Creating and manipulating Sets to store unique values, ensuring that duplicates are automatically removed. You used methods like
.add()
,.delete()
, and.clear()
to add, remove, and reset entries in the Set. - Checking and iterating over Set entries with methods like
.has()
and.forEach()
to verify the presence of items, display all entries, and iterate over elements efficiently. - Converting between Sets and Arrays to remove duplicates from arrays and retrieve unique values, demonstrating how Sets can be used in conjunction with arrays to handle collections more effectively.
- Automatic Uniqueness: Sets automatically enforce uniqueness, making them ideal for managing collections where duplicate values should be excluded, such as tags, categories, or IDs.
- Streamlined Data Management: Using Set methods allows for easy addition, deletion, and clearing of values, which simplifies data handling in comparison to arrays when duplicates are unwanted.
- Flexibility in Conversion: Converting between Sets and Arrays enables efficient duplicate removal from arrays, and allows Sets to be used interchangeably with arrays when necessary for other JavaScript operations.
With these skills, you’re now equipped to use JavaScript Sets to handle collections of unique data, improve data organization, and enhance the readability of your code. Continue practicing by using Sets in various projects, especially where uniqueness is critical, to develop more efficient and robust JavaScript applications!
🛑 Only use this as a reference 🛑
💾 Not something to copy and paste 💾
Note: This lab references a solution file located here (link not shown).
© All rights reserved to ThriveDX