Assignments Of Day 20: JavaScript Set and Map
Assignment 1: Working with Sets
Problem:
1. Create a
Set containing the numbers 1, 2, 3, 4, 5.
2. Add the
numbers 6 and 7 to the Set.
3. Remove
the number 3 from the Set.
4. Check if
the Set contains the number 2.
5. Clear the
Set.
6. Print the
Set at each step.
Solution:
javascript
Copy code
// Step 1: Create a Set with numbers 1, 2, 3, 4, 5
let mySet = new Set([1, 2, 3, 4, 5]);
console.log('Step 1:', mySet); // Set { 1, 2, 3, 4, 5 }
// Step 2: Add numbers 6 and 7 to the Set
mySet.add(6);
mySet.add(7);
console.log('Step 2:', mySet); // Set { 1, 2, 3, 4, 5, 6, 7 }
// Step 3: Remove the number 3 from the Set
mySet.delete(3);
console.log('Step 3:', mySet); // Set { 1, 2, 4, 5, 6, 7 }
// Step 4: Check if the Set contains the number 2
console.log('Step 4:', mySet.has(2)); // true
// Step 5: Clear the Set
mySet.clear();
console.log('Step 5:', mySet); // Set {}
Explanation:
1. A Set is
created containing the numbers 1, 2, 3, 4, 5. It doesn't allow duplicates.
2. The add()
method is used to add 6 and 7 to the Set.
3. The
delete() method is used to remove 3 from the Set.
4. The has()
method checks if the Set contains the number 2, which returns true.
5. The
clear() method removes all elements from the Set, leaving it empty.
Assignment
2: Working with Maps
Problem:
1. Create a
Map that holds a person's name, age, and email.
2. Add the
following key-value pairs:
o
name: "Alice"
o
age: 25
o
email: "alice@example.com"
3. Retrieve
the age and email from the Map and print them.
4. Check if
the Map contains the key name.
5. Remove
the key email from the Map.
6. Clear the
Map.
Solution:
javascript
Copy code
// Step 1: Create a Map
let personMap = new Map();
// Step 2: Add key-value pairs
personMap.set('name', 'Alice');
personMap.set('age', 25);
personMap.set('email', 'alice@example.com');
console.log('Step 2:', personMap);
// Step 3: Retrieve values for 'age' and 'email'
console.log('Step 3 - Age:',
personMap.get('age')); // 25
console.log('Step 3 - Email:',
personMap.get('email')); //
alice@example.com
// Step 4: Check if the Map contains the key 'name'
console.log('Step 4:', personMap.has('name')); // true
// Step 5: Remove the 'email' key-value pair
personMap.delete('email');
console.log('Step 5:', personMap);
// Step 6: Clear the Map
personMap.clear();
console.log('Step 6:', personMap); // Map {}
Explanation:
1. A Map
personMap is created to hold key-value pairs.
2. We use
the set() method to add key-value pairs for name, age, and email.
3. The get()
method retrieves the values for the age and email keys.
4. The has()
method checks if the key name exists in the Map, returning true.
5. The
delete() method removes the key-value pair for email.
6. The
clear() method removes all entries from the Map.
Assignment
3: Set Operations (Union and Intersection)
Problem:
1. Create
two Sets: setA and setB. Initialize them with the following values:
o
setA: {1, 2, 3, 4, 5}
o
setB: {4, 5, 6, 7, 8}
2. Perform
the following operations:
o
Union: Create a new Set that contains
all unique elements from both sets.
o
Intersection: Create a new Set that contains
only the elements that appear in both sets.
3. Print the
results of both operations.
Solution:
javascript
Copy code
// Step 1: Create two Sets
let setA = new Set([1, 2, 3, 4, 5]);
let setB = new Set([4, 5, 6, 7, 8]);
// Step 2: Union of setA and setB
let unionSet = new Set([...setA, ...setB]);
console.log('Union:', unionSet); // Set { 1, 2, 3, 4, 5, 6, 7, 8 }
// Step 3: Intersection of setA and setB
let intersectionSet = new Set([...setA].filter(x
=> setB.has(x)));
console.log('Intersection:', intersectionSet); // Set { 4, 5 }
Explanation:
1. Two Sets
setA and setB are created with the given values.
2. The Union
of the two Sets is created by spreading both Sets into a new Set. This combines
the elements of both Sets without duplicates.
3. The Intersection
is created by filtering the elements of setA to keep only those elements that
also exist in setB (using the has() method).
Assignment
4: Map Key-Value Pair Manipulation
Problem:
1. Create a
Map called studentMap to store the following student data:
o
ID: 101, Name: John
o
ID: 102, Name: Jane
o
ID: 103, Name: Jack
2. Add a new
student with ID 104 and Name Jill.
3. Update
the Name of the student with ID 102 to Janet.
4. Delete
the student with ID 103.
5. Print all
student data after each modification.
Solution:
javascript
Copy code
// Step 1: Create a Map with student data
let studentMap = new Map();
studentMap.set(101, 'John');
studentMap.set(102, 'Jane');
studentMap.set(103, 'Jack');
console.log('Step 1:', studentMap);
// Step 2: Add a new student
studentMap.set(104, 'Jill');
console.log('Step 2:', studentMap);
// Step 3: Update the name of student with ID 102
studentMap.set(102, 'Janet');
console.log('Step 3:', studentMap);
// Step 4: Delete the student with ID 103
studentMap.delete(103);
console.log('Step 4:', studentMap);
Explanation:
1. A Map
studentMap is created with key-value pairs where the key is the student ID and
the value is the student's name.
2. A new
student with ID 104 is added using the set() method.
3. The name
of the student with ID 102 is updated by calling set() again with the new name.
4. The
student with ID 103 is removed using the delete() method.
Assignment
5: Iterating Over a Map
Problem:
1. Create a
Map with the following student data:
o
ID: 101, Name: John
o
ID: 102, Name: Jane
o
ID: 103, Name: Jack
2. Write a
function to print all student names using iteration over the Map.
Solution:
javascript
Copy code
// Step 1: Create a Map with student data
let studentMap = new Map();
studentMap.set(101, 'John');
studentMap.set(102, 'Jane');
studentMap.set(103, 'Jack');
// Step 2: Iterate over the Map and print names
studentMap.forEach((value, key) => {
console.log(`Student ID: ${key}, Name: ${value}`);
});
Explanation:
1. A Map
studentMap is created with student IDs as keys and names as values.
2. The
forEach() method is used to iterate over the Map. For each entry, the key (ID)
and value (Name) are printed.
These
assignments will give students hands-on experience with Set and Map
operations, which are useful for managing collections of data in JavaScript
efficiently. The assignments range from basic operations like adding and
removing elements to more advanced tasks like union and intersection of Sets
and iteration over Maps.
4o mini
You said:
more
ChatGPT
said:
ChatGPT
Here are
additional assignments with solutions on JavaScript Set and Map
concepts:
Assignment
6: Set Operations (Difference and Symmetric Difference)
Problem:
1. Create
two Sets: setX and setY. Initialize them with the following values:
o
setX: {1, 2, 3, 4, 5}
o
setY: {4, 5, 6, 7, 8}
2. Perform
the following operations:
o
Difference: Create a new Set that contains
the elements that are in setX but not in setY.
o
Symmetric Difference: Create
a new Set that contains the elements that are in either setX or setY, but not
in both.
3. Print the
results of both operations.
Solution:
javascript
Copy code
// Step 1: Create two Sets
let setX = new Set([1, 2, 3, 4, 5]);
let setY = new Set([4, 5, 6, 7, 8]);
// Step 2: Difference (setX - setY)
let differenceSet = new Set([...setX].filter(x
=> !setY.has(x)));
console.log('Difference:', differenceSet); // Set { 1, 2, 3 }
// Step 3: Symmetric Difference (elements in either
set, but not both)
let symmetricDifferenceSet = new Set([
...[...setX].filter(x => !setY.has(x)),
...[...setY].filter(x => !setX.has(x))
]);
console.log('Symmetric Difference:',
symmetricDifferenceSet); // Set { 1, 2,
3, 6, 7, 8 }
Explanation:
1. The Difference
of setX and setY is found by filtering elements in setX that do not exist in
setY.
2. The Symmetric
Difference is created by filtering the elements of setX and setY separately
and combining the results, thus eliminating elements that exist in both Sets.
Assignment
7: Map Iteration with for...of Loop
Problem:
1. Create a
Map called fruitPrices to store the prices of different fruits:
o
apple: 1.5
o
banana: 0.5
o
orange: 0.75
2. Use the
for...of loop to iterate through the Map and print the fruit name and its price.
Solution:
javascript
Copy code
// Step 1: Create a Map with fruit prices
let fruitPrices = new Map();
fruitPrices.set('apple', 1.5);
fruitPrices.set('banana', 0.5);
fruitPrices.set('orange', 0.75);
// Step 2: Iterate over the Map using for...of loop
for (let [fruit, price] of fruitPrices) {
console.log(`${fruit}: $${price}`);
}
Explanation:
1. A Map
fruitPrices is created to store fruit names as keys and prices as values.
2. The
for...of loop is used to iterate over the Map. Each iteration gives the fruit
and price, which are printed.
Assignment
8: Set and Map Combined Example
Problem:
1. Create a
Set mySet with the following values: 1, 2, 3, 4.
2. Create a
Map myMap with the following key-value pairs:
o
id: 101, name: 'John'
o
id: 102, name: 'Jane'
o
id: 103, name: 'Jack'
3. Use the
forEach() method to iterate over the Set and the Map:
o
For the Set: Print each number.
o
For the Map: Print the student ID and their name.
Solution:
javascript
Copy code
// Step 1: Create a Set
let mySet = new Set([1, 2, 3, 4]);
// Step 2: Iterate over the Set using forEach()
mySet.forEach(value => {
console.log('Set Value:', value);
});
// Step 3: Create a Map with student data
let myMap = new Map([
[101,
'John'],
[102,
'Jane'],
[103,
'Jack']
]);
// Step 4: Iterate over the Map using forEach()
myMap.forEach((value, key) => {
console.log(`Student ID: ${key}, Name: ${value}`);
});
Explanation:
1. A Set
mySet is created and the forEach() method is used to print each value.
2. A Map
myMap is created to hold student IDs and names. The forEach() method iterates
through the Map, printing both the ID and name for each entry.
Assignment
9: Working with Map and Set Together
Problem:
1. Create a
Map userMap where the key is a user ID (integer) and the value is the user’s
name.
o
Add the following user details:
§ User ID:
1, Name: Alice
§ User ID:
2, Name: Bob
§ User ID:
3, Name: Charlie
2. Create a
Set loggedInUsers to store the IDs of users who are currently logged in:
o
1, 3
3. Write a
function getLoggedInUserNames that takes the Map and Set as parameters and
returns an array of names of users who are logged in.
Solution:
javascript
Copy code
// Step 1: Create a Map with user IDs and names
let userMap = new Map([
[1,
'Alice'],
[2, 'Bob'],
[3,
'Charlie']
]);
// Step 2: Create a Set with logged-in user IDs
let loggedInUsers = new Set([1, 3]);
// Step 3: Define a function to get names of
logged-in users
function getLoggedInUserNames(map, set) {
let
loggedInNames = [];
set.forEach(id => {
if
(map.has(id)) {
loggedInNames.push(map.get(id));
}
});
return
loggedInNames;
}
// Step 4: Call the function and log the result
console.log(getLoggedInUserNames(userMap,
loggedInUsers)); // ['Alice', 'Charlie']
Explanation:
1. A Map
userMap is created to store user IDs and names.
2. A Set
loggedInUsers contains the IDs of logged-in users.
3. The
function getLoggedInUserNames loops through the Set, and for each ID, it checks
if the Map contains that ID. If it does, the name is added to the result array.
4. The
function returns an array of names of the logged-in users.
Assignment
10: Removing Duplicate Values Using Set
Problem:
1. Create an
array numbers with the following values: [1, 2, 3, 3, 4, 4, 5].
2. Convert
the array into a Set to remove duplicates.
3. Convert
the Set back into an array and print the result.
Solution:
javascript
Copy code
// Step 1: Create an array with duplicate values
let numbers = [1, 2, 3, 3, 4, 4, 5];
// Step 2: Convert the array into a Set to remove
duplicates
let uniqueNumbers = new Set(numbers);
// Step 3: Convert the Set back into an array
let uniqueNumbersArray = [...uniqueNumbers];
console.log(uniqueNumbersArray); // [1, 2, 3, 4, 5]
Explanation:
1. An array
numbers is created with duplicate values.
2. The array
is converted into a Set, which automatically removes the duplicates.
3. The Set
is converted back into an array using the spread operator (...), resulting in
an array with only unique values.
